##// END OF EJS Templates
Add GeoJSON display class
Grant Nestor -
Show More
@@ -1,1133 +1,1152
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Top-level display functions for displaying object in different formats."""
2 """Top-level display functions for displaying object in different formats."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 try:
8 try:
9 from base64 import encodebytes as base64_encode
9 from base64 import encodebytes as base64_encode
10 except ImportError:
10 except ImportError:
11 from base64 import encodestring as base64_encode
11 from base64 import encodestring as base64_encode
12
12
13 from binascii import b2a_hex
13 from binascii import b2a_hex
14 import json
14 import json
15 import mimetypes
15 import mimetypes
16 import os
16 import os
17 import struct
17 import struct
18 import sys
18 import sys
19 import warnings
19 import warnings
20
20
21 from IPython.utils.py3compat import cast_bytes_py2, cast_unicode
21 from IPython.utils.py3compat import cast_bytes_py2, cast_unicode
22 from IPython.testing.skipdoctest import skip_doctest
22 from IPython.testing.skipdoctest import skip_doctest
23
23
24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'GeoJSON', 'Javascript',
28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
29 'publish_display_data', 'update_display', 'DisplayHandle']
29 'publish_display_data', 'update_display', 'DisplayHandle']
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # utility functions
32 # utility functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 def _safe_exists(path):
35 def _safe_exists(path):
36 """Check path, but don't let exceptions raise"""
36 """Check path, but don't let exceptions raise"""
37 try:
37 try:
38 return os.path.exists(path)
38 return os.path.exists(path)
39 except Exception:
39 except Exception:
40 return False
40 return False
41
41
42 def _merge(d1, d2):
42 def _merge(d1, d2):
43 """Like update, but merges sub-dicts instead of clobbering at the top level.
43 """Like update, but merges sub-dicts instead of clobbering at the top level.
44
44
45 Updates d1 in-place
45 Updates d1 in-place
46 """
46 """
47
47
48 if not isinstance(d2, dict) or not isinstance(d1, dict):
48 if not isinstance(d2, dict) or not isinstance(d1, dict):
49 return d2
49 return d2
50 for key, value in d2.items():
50 for key, value in d2.items():
51 d1[key] = _merge(d1.get(key), value)
51 d1[key] = _merge(d1.get(key), value)
52 return d1
52 return d1
53
53
54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
55 """internal implementation of all display_foo methods
55 """internal implementation of all display_foo methods
56
56
57 Parameters
57 Parameters
58 ----------
58 ----------
59 mimetype : str
59 mimetype : str
60 The mimetype to be published (e.g. 'image/png')
60 The mimetype to be published (e.g. 'image/png')
61 objs : tuple of objects
61 objs : tuple of objects
62 The Python objects to display, or if raw=True raw text data to
62 The Python objects to display, or if raw=True raw text data to
63 display.
63 display.
64 raw : bool
64 raw : bool
65 Are the data objects raw data or Python objects that need to be
65 Are the data objects raw data or Python objects that need to be
66 formatted before display? [default: False]
66 formatted before display? [default: False]
67 metadata : dict (optional)
67 metadata : dict (optional)
68 Metadata to be associated with the specific mimetype output.
68 Metadata to be associated with the specific mimetype output.
69 """
69 """
70 if metadata:
70 if metadata:
71 metadata = {mimetype: metadata}
71 metadata = {mimetype: metadata}
72 if raw:
72 if raw:
73 # turn list of pngdata into list of { 'image/png': pngdata }
73 # turn list of pngdata into list of { 'image/png': pngdata }
74 objs = [ {mimetype: obj} for obj in objs ]
74 objs = [ {mimetype: obj} for obj in objs ]
75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Main functions
78 # Main functions
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # use * to indicate transient is keyword-only
81 # use * to indicate transient is keyword-only
82 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
82 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
83 """Publish data and metadata to all frontends.
83 """Publish data and metadata to all frontends.
84
84
85 See the ``display_data`` message in the messaging documentation for
85 See the ``display_data`` message in the messaging documentation for
86 more details about this message type.
86 more details about this message type.
87
87
88 The following MIME types are currently implemented:
88 The following MIME types are currently implemented:
89
89
90 * text/plain
90 * text/plain
91 * text/html
91 * text/html
92 * text/markdown
92 * text/markdown
93 * text/latex
93 * text/latex
94 * application/json
94 * application/json
95 * application/javascript
95 * application/javascript
96 * image/png
96 * image/png
97 * image/jpeg
97 * image/jpeg
98 * image/svg+xml
98 * image/svg+xml
99
99
100 Parameters
100 Parameters
101 ----------
101 ----------
102 data : dict
102 data : dict
103 A dictionary having keys that are valid MIME types (like
103 A dictionary having keys that are valid MIME types (like
104 'text/plain' or 'image/svg+xml') and values that are the data for
104 'text/plain' or 'image/svg+xml') and values that are the data for
105 that MIME type. The data itself must be a JSON'able data
105 that MIME type. The data itself must be a JSON'able data
106 structure. Minimally all data should have the 'text/plain' data,
106 structure. Minimally all data should have the 'text/plain' data,
107 which can be displayed by all frontends. If more than the plain
107 which can be displayed by all frontends. If more than the plain
108 text is given, it is up to the frontend to decide which
108 text is given, it is up to the frontend to decide which
109 representation to use.
109 representation to use.
110 metadata : dict
110 metadata : dict
111 A dictionary for metadata related to the data. This can contain
111 A dictionary for metadata related to the data. This can contain
112 arbitrary key, value pairs that frontends can use to interpret
112 arbitrary key, value pairs that frontends can use to interpret
113 the data. mime-type keys matching those in data can be used
113 the data. mime-type keys matching those in data can be used
114 to specify metadata about particular representations.
114 to specify metadata about particular representations.
115 source : str, deprecated
115 source : str, deprecated
116 Unused.
116 Unused.
117 transient : dict, keyword-only
117 transient : dict, keyword-only
118 A dictionary of transient data, such as display_id.
118 A dictionary of transient data, such as display_id.
119 """
119 """
120 from IPython.core.interactiveshell import InteractiveShell
120 from IPython.core.interactiveshell import InteractiveShell
121
121
122 display_pub = InteractiveShell.instance().display_pub
122 display_pub = InteractiveShell.instance().display_pub
123
123
124 # only pass transient if supplied,
124 # only pass transient if supplied,
125 # to avoid errors with older ipykernel.
125 # to avoid errors with older ipykernel.
126 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
126 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
127 if transient:
127 if transient:
128 kwargs['transient'] = transient
128 kwargs['transient'] = transient
129
129
130 display_pub.publish(
130 display_pub.publish(
131 data=data,
131 data=data,
132 metadata=metadata,
132 metadata=metadata,
133 **kwargs
133 **kwargs
134 )
134 )
135
135
136
136
137 def _new_id():
137 def _new_id():
138 """Generate a new random text id with urandom"""
138 """Generate a new random text id with urandom"""
139 return b2a_hex(os.urandom(16)).decode('ascii')
139 return b2a_hex(os.urandom(16)).decode('ascii')
140
140
141
141
142 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
142 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
143 """Display a Python object in all frontends.
143 """Display a Python object in all frontends.
144
144
145 By default all representations will be computed and sent to the frontends.
145 By default all representations will be computed and sent to the frontends.
146 Frontends can decide which representation is used and how.
146 Frontends can decide which representation is used and how.
147
147
148 Parameters
148 Parameters
149 ----------
149 ----------
150 objs : tuple of objects
150 objs : tuple of objects
151 The Python objects to display.
151 The Python objects to display.
152 raw : bool, optional
152 raw : bool, optional
153 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
153 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
154 or Python objects that need to be formatted before display? [default: False]
154 or Python objects that need to be formatted before display? [default: False]
155 include : list or tuple, optional
155 include : list or tuple, optional
156 A list of format type strings (MIME types) to include in the
156 A list of format type strings (MIME types) to include in the
157 format data dict. If this is set *only* the format types included
157 format data dict. If this is set *only* the format types included
158 in this list will be computed.
158 in this list will be computed.
159 exclude : list or tuple, optional
159 exclude : list or tuple, optional
160 A list of format type strings (MIME types) to exclude in the format
160 A list of format type strings (MIME types) to exclude in the format
161 data dict. If this is set all format types will be computed,
161 data dict. If this is set all format types will be computed,
162 except for those included in this argument.
162 except for those included in this argument.
163 metadata : dict, optional
163 metadata : dict, optional
164 A dictionary of metadata to associate with the output.
164 A dictionary of metadata to associate with the output.
165 mime-type keys in this dictionary will be associated with the individual
165 mime-type keys in this dictionary will be associated with the individual
166 representation formats, if they exist.
166 representation formats, if they exist.
167 transient : dict, optional
167 transient : dict, optional
168 A dictionary of transient data to associate with the output.
168 A dictionary of transient data to associate with the output.
169 Data in this dict should not be persisted to files (e.g. notebooks).
169 Data in this dict should not be persisted to files (e.g. notebooks).
170 display_id : str, optional
170 display_id : str, optional
171 Set an id for the display.
171 Set an id for the display.
172 This id can be used for updating this display area later via update_display.
172 This id can be used for updating this display area later via update_display.
173 If given as True, generate a new display_id
173 If given as True, generate a new display_id
174 kwargs: additional keyword-args, optional
174 kwargs: additional keyword-args, optional
175 Additional keyword-arguments are passed through to the display publisher.
175 Additional keyword-arguments are passed through to the display publisher.
176
176
177 Returns
177 Returns
178 -------
178 -------
179
179
180 handle: DisplayHandle
180 handle: DisplayHandle
181 Returns a handle on updatable displays, if display_id is given.
181 Returns a handle on updatable displays, if display_id is given.
182 Returns None if no display_id is given (default).
182 Returns None if no display_id is given (default).
183 """
183 """
184 raw = kwargs.pop('raw', False)
184 raw = kwargs.pop('raw', False)
185 if transient is None:
185 if transient is None:
186 transient = {}
186 transient = {}
187 if display_id:
187 if display_id:
188 if display_id == True:
188 if display_id == True:
189 display_id = _new_id()
189 display_id = _new_id()
190 transient['display_id'] = display_id
190 transient['display_id'] = display_id
191 if kwargs.get('update') and 'display_id' not in transient:
191 if kwargs.get('update') and 'display_id' not in transient:
192 raise TypeError('display_id required for update_display')
192 raise TypeError('display_id required for update_display')
193 if transient:
193 if transient:
194 kwargs['transient'] = transient
194 kwargs['transient'] = transient
195
195
196 from IPython.core.interactiveshell import InteractiveShell
196 from IPython.core.interactiveshell import InteractiveShell
197
197
198 if not raw:
198 if not raw:
199 format = InteractiveShell.instance().display_formatter.format
199 format = InteractiveShell.instance().display_formatter.format
200
200
201 for obj in objs:
201 for obj in objs:
202 if raw:
202 if raw:
203 publish_display_data(data=obj, metadata=metadata, **kwargs)
203 publish_display_data(data=obj, metadata=metadata, **kwargs)
204 else:
204 else:
205 format_dict, md_dict = format(obj, include=include, exclude=exclude)
205 format_dict, md_dict = format(obj, include=include, exclude=exclude)
206 if not format_dict:
206 if not format_dict:
207 # nothing to display (e.g. _ipython_display_ took over)
207 # nothing to display (e.g. _ipython_display_ took over)
208 continue
208 continue
209 if metadata:
209 if metadata:
210 # kwarg-specified metadata gets precedence
210 # kwarg-specified metadata gets precedence
211 _merge(md_dict, metadata)
211 _merge(md_dict, metadata)
212 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
212 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
213 if display_id:
213 if display_id:
214 return DisplayHandle(display_id)
214 return DisplayHandle(display_id)
215
215
216
216
217 # use * for keyword-only display_id arg
217 # use * for keyword-only display_id arg
218 def update_display(obj, *, display_id, **kwargs):
218 def update_display(obj, *, display_id, **kwargs):
219 """Update an existing display by id
219 """Update an existing display by id
220
220
221 Parameters
221 Parameters
222 ----------
222 ----------
223
223
224 obj:
224 obj:
225 The object with which to update the display
225 The object with which to update the display
226 display_id: keyword-only
226 display_id: keyword-only
227 The id of the display to update
227 The id of the display to update
228 """
228 """
229 kwargs['update'] = True
229 kwargs['update'] = True
230 display(obj, display_id=display_id, **kwargs)
230 display(obj, display_id=display_id, **kwargs)
231
231
232
232
233 class DisplayHandle(object):
233 class DisplayHandle(object):
234 """A handle on an updatable display
234 """A handle on an updatable display
235
235
236 Call .update(obj) to display a new object.
236 Call .update(obj) to display a new object.
237
237
238 Call .display(obj) to add a new instance of this display,
238 Call .display(obj) to add a new instance of this display,
239 and update existing instances.
239 and update existing instances.
240 """
240 """
241
241
242 def __init__(self, display_id=None):
242 def __init__(self, display_id=None):
243 if display_id is None:
243 if display_id is None:
244 display_id = _new_id()
244 display_id = _new_id()
245 self.display_id = display_id
245 self.display_id = display_id
246
246
247 def __repr__(self):
247 def __repr__(self):
248 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
248 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
249
249
250 def display(self, obj, **kwargs):
250 def display(self, obj, **kwargs):
251 """Make a new display with my id, updating existing instances.
251 """Make a new display with my id, updating existing instances.
252
252
253 Parameters
253 Parameters
254 ----------
254 ----------
255
255
256 obj:
256 obj:
257 object to display
257 object to display
258 **kwargs:
258 **kwargs:
259 additional keyword arguments passed to display
259 additional keyword arguments passed to display
260 """
260 """
261 display(obj, display_id=self.display_id, **kwargs)
261 display(obj, display_id=self.display_id, **kwargs)
262
262
263 def update(self, obj, **kwargs):
263 def update(self, obj, **kwargs):
264 """Update existing displays with my id
264 """Update existing displays with my id
265
265
266 Parameters
266 Parameters
267 ----------
267 ----------
268
268
269 obj:
269 obj:
270 object to display
270 object to display
271 **kwargs:
271 **kwargs:
272 additional keyword arguments passed to update_display
272 additional keyword arguments passed to update_display
273 """
273 """
274 update_display(obj, display_id=self.display_id, **kwargs)
274 update_display(obj, display_id=self.display_id, **kwargs)
275
275
276
276
277 def display_pretty(*objs, **kwargs):
277 def display_pretty(*objs, **kwargs):
278 """Display the pretty (default) representation of an object.
278 """Display the pretty (default) representation of an object.
279
279
280 Parameters
280 Parameters
281 ----------
281 ----------
282 objs : tuple of objects
282 objs : tuple of objects
283 The Python objects to display, or if raw=True raw text data to
283 The Python objects to display, or if raw=True raw text data to
284 display.
284 display.
285 raw : bool
285 raw : bool
286 Are the data objects raw data or Python objects that need to be
286 Are the data objects raw data or Python objects that need to be
287 formatted before display? [default: False]
287 formatted before display? [default: False]
288 metadata : dict (optional)
288 metadata : dict (optional)
289 Metadata to be associated with the specific mimetype output.
289 Metadata to be associated with the specific mimetype output.
290 """
290 """
291 _display_mimetype('text/plain', objs, **kwargs)
291 _display_mimetype('text/plain', objs, **kwargs)
292
292
293
293
294 def display_html(*objs, **kwargs):
294 def display_html(*objs, **kwargs):
295 """Display the HTML representation of an object.
295 """Display the HTML representation of an object.
296
296
297 Note: If raw=False and the object does not have a HTML
297 Note: If raw=False and the object does not have a HTML
298 representation, no HTML will be shown.
298 representation, no HTML will be shown.
299
299
300 Parameters
300 Parameters
301 ----------
301 ----------
302 objs : tuple of objects
302 objs : tuple of objects
303 The Python objects to display, or if raw=True raw HTML data to
303 The Python objects to display, or if raw=True raw HTML data to
304 display.
304 display.
305 raw : bool
305 raw : bool
306 Are the data objects raw data or Python objects that need to be
306 Are the data objects raw data or Python objects that need to be
307 formatted before display? [default: False]
307 formatted before display? [default: False]
308 metadata : dict (optional)
308 metadata : dict (optional)
309 Metadata to be associated with the specific mimetype output.
309 Metadata to be associated with the specific mimetype output.
310 """
310 """
311 _display_mimetype('text/html', objs, **kwargs)
311 _display_mimetype('text/html', objs, **kwargs)
312
312
313
313
314 def display_markdown(*objs, **kwargs):
314 def display_markdown(*objs, **kwargs):
315 """Displays the Markdown representation of an object.
315 """Displays the Markdown representation of an object.
316
316
317 Parameters
317 Parameters
318 ----------
318 ----------
319 objs : tuple of objects
319 objs : tuple of objects
320 The Python objects to display, or if raw=True raw markdown data to
320 The Python objects to display, or if raw=True raw markdown data to
321 display.
321 display.
322 raw : bool
322 raw : bool
323 Are the data objects raw data or Python objects that need to be
323 Are the data objects raw data or Python objects that need to be
324 formatted before display? [default: False]
324 formatted before display? [default: False]
325 metadata : dict (optional)
325 metadata : dict (optional)
326 Metadata to be associated with the specific mimetype output.
326 Metadata to be associated with the specific mimetype output.
327 """
327 """
328
328
329 _display_mimetype('text/markdown', objs, **kwargs)
329 _display_mimetype('text/markdown', objs, **kwargs)
330
330
331
331
332 def display_svg(*objs, **kwargs):
332 def display_svg(*objs, **kwargs):
333 """Display the SVG representation of an object.
333 """Display the SVG representation of an object.
334
334
335 Parameters
335 Parameters
336 ----------
336 ----------
337 objs : tuple of objects
337 objs : tuple of objects
338 The Python objects to display, or if raw=True raw svg data to
338 The Python objects to display, or if raw=True raw svg data to
339 display.
339 display.
340 raw : bool
340 raw : bool
341 Are the data objects raw data or Python objects that need to be
341 Are the data objects raw data or Python objects that need to be
342 formatted before display? [default: False]
342 formatted before display? [default: False]
343 metadata : dict (optional)
343 metadata : dict (optional)
344 Metadata to be associated with the specific mimetype output.
344 Metadata to be associated with the specific mimetype output.
345 """
345 """
346 _display_mimetype('image/svg+xml', objs, **kwargs)
346 _display_mimetype('image/svg+xml', objs, **kwargs)
347
347
348
348
349 def display_png(*objs, **kwargs):
349 def display_png(*objs, **kwargs):
350 """Display the PNG representation of an object.
350 """Display the PNG representation of an object.
351
351
352 Parameters
352 Parameters
353 ----------
353 ----------
354 objs : tuple of objects
354 objs : tuple of objects
355 The Python objects to display, or if raw=True raw png data to
355 The Python objects to display, or if raw=True raw png data to
356 display.
356 display.
357 raw : bool
357 raw : bool
358 Are the data objects raw data or Python objects that need to be
358 Are the data objects raw data or Python objects that need to be
359 formatted before display? [default: False]
359 formatted before display? [default: False]
360 metadata : dict (optional)
360 metadata : dict (optional)
361 Metadata to be associated with the specific mimetype output.
361 Metadata to be associated with the specific mimetype output.
362 """
362 """
363 _display_mimetype('image/png', objs, **kwargs)
363 _display_mimetype('image/png', objs, **kwargs)
364
364
365
365
366 def display_jpeg(*objs, **kwargs):
366 def display_jpeg(*objs, **kwargs):
367 """Display the JPEG representation of an object.
367 """Display the JPEG representation of an object.
368
368
369 Parameters
369 Parameters
370 ----------
370 ----------
371 objs : tuple of objects
371 objs : tuple of objects
372 The Python objects to display, or if raw=True raw JPEG data to
372 The Python objects to display, or if raw=True raw JPEG data to
373 display.
373 display.
374 raw : bool
374 raw : bool
375 Are the data objects raw data or Python objects that need to be
375 Are the data objects raw data or Python objects that need to be
376 formatted before display? [default: False]
376 formatted before display? [default: False]
377 metadata : dict (optional)
377 metadata : dict (optional)
378 Metadata to be associated with the specific mimetype output.
378 Metadata to be associated with the specific mimetype output.
379 """
379 """
380 _display_mimetype('image/jpeg', objs, **kwargs)
380 _display_mimetype('image/jpeg', objs, **kwargs)
381
381
382
382
383 def display_latex(*objs, **kwargs):
383 def display_latex(*objs, **kwargs):
384 """Display the LaTeX representation of an object.
384 """Display the LaTeX representation of an object.
385
385
386 Parameters
386 Parameters
387 ----------
387 ----------
388 objs : tuple of objects
388 objs : tuple of objects
389 The Python objects to display, or if raw=True raw latex data to
389 The Python objects to display, or if raw=True raw latex data to
390 display.
390 display.
391 raw : bool
391 raw : bool
392 Are the data objects raw data or Python objects that need to be
392 Are the data objects raw data or Python objects that need to be
393 formatted before display? [default: False]
393 formatted before display? [default: False]
394 metadata : dict (optional)
394 metadata : dict (optional)
395 Metadata to be associated with the specific mimetype output.
395 Metadata to be associated with the specific mimetype output.
396 """
396 """
397 _display_mimetype('text/latex', objs, **kwargs)
397 _display_mimetype('text/latex', objs, **kwargs)
398
398
399
399
400 def display_json(*objs, **kwargs):
400 def display_json(*objs, **kwargs):
401 """Display the JSON representation of an object.
401 """Display the JSON representation of an object.
402
402
403 Note that not many frontends support displaying JSON.
403 Note that not many frontends support displaying JSON.
404
404
405 Parameters
405 Parameters
406 ----------
406 ----------
407 objs : tuple of objects
407 objs : tuple of objects
408 The Python objects to display, or if raw=True raw json data to
408 The Python objects to display, or if raw=True raw json data to
409 display.
409 display.
410 raw : bool
410 raw : bool
411 Are the data objects raw data or Python objects that need to be
411 Are the data objects raw data or Python objects that need to be
412 formatted before display? [default: False]
412 formatted before display? [default: False]
413 metadata : dict (optional)
413 metadata : dict (optional)
414 Metadata to be associated with the specific mimetype output.
414 Metadata to be associated with the specific mimetype output.
415 """
415 """
416 _display_mimetype('application/json', objs, **kwargs)
416 _display_mimetype('application/json', objs, **kwargs)
417
417
418
418
419 def display_javascript(*objs, **kwargs):
419 def display_javascript(*objs, **kwargs):
420 """Display the Javascript representation of an object.
420 """Display the Javascript representation of an object.
421
421
422 Parameters
422 Parameters
423 ----------
423 ----------
424 objs : tuple of objects
424 objs : tuple of objects
425 The Python objects to display, or if raw=True raw javascript data to
425 The Python objects to display, or if raw=True raw javascript data to
426 display.
426 display.
427 raw : bool
427 raw : bool
428 Are the data objects raw data or Python objects that need to be
428 Are the data objects raw data or Python objects that need to be
429 formatted before display? [default: False]
429 formatted before display? [default: False]
430 metadata : dict (optional)
430 metadata : dict (optional)
431 Metadata to be associated with the specific mimetype output.
431 Metadata to be associated with the specific mimetype output.
432 """
432 """
433 _display_mimetype('application/javascript', objs, **kwargs)
433 _display_mimetype('application/javascript', objs, **kwargs)
434
434
435
435
436 def display_pdf(*objs, **kwargs):
436 def display_pdf(*objs, **kwargs):
437 """Display the PDF representation of an object.
437 """Display the PDF representation of an object.
438
438
439 Parameters
439 Parameters
440 ----------
440 ----------
441 objs : tuple of objects
441 objs : tuple of objects
442 The Python objects to display, or if raw=True raw javascript data to
442 The Python objects to display, or if raw=True raw javascript data to
443 display.
443 display.
444 raw : bool
444 raw : bool
445 Are the data objects raw data or Python objects that need to be
445 Are the data objects raw data or Python objects that need to be
446 formatted before display? [default: False]
446 formatted before display? [default: False]
447 metadata : dict (optional)
447 metadata : dict (optional)
448 Metadata to be associated with the specific mimetype output.
448 Metadata to be associated with the specific mimetype output.
449 """
449 """
450 _display_mimetype('application/pdf', objs, **kwargs)
450 _display_mimetype('application/pdf', objs, **kwargs)
451
451
452
452
453 #-----------------------------------------------------------------------------
453 #-----------------------------------------------------------------------------
454 # Smart classes
454 # Smart classes
455 #-----------------------------------------------------------------------------
455 #-----------------------------------------------------------------------------
456
456
457
457
458 class DisplayObject(object):
458 class DisplayObject(object):
459 """An object that wraps data to be displayed."""
459 """An object that wraps data to be displayed."""
460
460
461 _read_flags = 'r'
461 _read_flags = 'r'
462 _show_mem_addr = False
462 _show_mem_addr = False
463
463
464 def __init__(self, data=None, url=None, filename=None):
464 def __init__(self, data=None, url=None, filename=None):
465 """Create a display object given raw data.
465 """Create a display object given raw data.
466
466
467 When this object is returned by an expression or passed to the
467 When this object is returned by an expression or passed to the
468 display function, it will result in the data being displayed
468 display function, it will result in the data being displayed
469 in the frontend. The MIME type of the data should match the
469 in the frontend. The MIME type of the data should match the
470 subclasses used, so the Png subclass should be used for 'image/png'
470 subclasses used, so the Png subclass should be used for 'image/png'
471 data. If the data is a URL, the data will first be downloaded
471 data. If the data is a URL, the data will first be downloaded
472 and then displayed. If
472 and then displayed. If
473
473
474 Parameters
474 Parameters
475 ----------
475 ----------
476 data : unicode, str or bytes
476 data : unicode, str or bytes
477 The raw data or a URL or file to load the data from
477 The raw data or a URL or file to load the data from
478 url : unicode
478 url : unicode
479 A URL to download the data from.
479 A URL to download the data from.
480 filename : unicode
480 filename : unicode
481 Path to a local file to load the data from.
481 Path to a local file to load the data from.
482 """
482 """
483 if data is not None and isinstance(data, str):
483 if data is not None and isinstance(data, str):
484 if data.startswith('http') and url is None:
484 if data.startswith('http') and url is None:
485 url = data
485 url = data
486 filename = None
486 filename = None
487 data = None
487 data = None
488 elif _safe_exists(data) and filename is None:
488 elif _safe_exists(data) and filename is None:
489 url = None
489 url = None
490 filename = data
490 filename = data
491 data = None
491 data = None
492
492
493 self.data = data
493 self.data = data
494 self.url = url
494 self.url = url
495 self.filename = filename
495 self.filename = filename
496
496
497 self.reload()
497 self.reload()
498 self._check_data()
498 self._check_data()
499
499
500 def __repr__(self):
500 def __repr__(self):
501 if not self._show_mem_addr:
501 if not self._show_mem_addr:
502 cls = self.__class__
502 cls = self.__class__
503 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
503 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
504 else:
504 else:
505 r = super(DisplayObject, self).__repr__()
505 r = super(DisplayObject, self).__repr__()
506 return r
506 return r
507
507
508 def _check_data(self):
508 def _check_data(self):
509 """Override in subclasses if there's something to check."""
509 """Override in subclasses if there's something to check."""
510 pass
510 pass
511
511
512 def reload(self):
512 def reload(self):
513 """Reload the raw data from file or URL."""
513 """Reload the raw data from file or URL."""
514 if self.filename is not None:
514 if self.filename is not None:
515 with open(self.filename, self._read_flags) as f:
515 with open(self.filename, self._read_flags) as f:
516 self.data = f.read()
516 self.data = f.read()
517 elif self.url is not None:
517 elif self.url is not None:
518 try:
518 try:
519 # Deferred import
519 # Deferred import
520 from urllib.request import urlopen
520 from urllib.request import urlopen
521 response = urlopen(self.url)
521 response = urlopen(self.url)
522 self.data = response.read()
522 self.data = response.read()
523 # extract encoding from header, if there is one:
523 # extract encoding from header, if there is one:
524 encoding = None
524 encoding = None
525 for sub in response.headers['content-type'].split(';'):
525 for sub in response.headers['content-type'].split(';'):
526 sub = sub.strip()
526 sub = sub.strip()
527 if sub.startswith('charset'):
527 if sub.startswith('charset'):
528 encoding = sub.split('=')[-1].strip()
528 encoding = sub.split('=')[-1].strip()
529 break
529 break
530 # decode data, if an encoding was specified
530 # decode data, if an encoding was specified
531 if encoding:
531 if encoding:
532 self.data = self.data.decode(encoding, 'replace')
532 self.data = self.data.decode(encoding, 'replace')
533 except:
533 except:
534 self.data = None
534 self.data = None
535
535
536 class TextDisplayObject(DisplayObject):
536 class TextDisplayObject(DisplayObject):
537 """Validate that display data is text"""
537 """Validate that display data is text"""
538 def _check_data(self):
538 def _check_data(self):
539 if self.data is not None and not isinstance(self.data, str):
539 if self.data is not None and not isinstance(self.data, str):
540 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
540 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
541
541
542 class Pretty(TextDisplayObject):
542 class Pretty(TextDisplayObject):
543
543
544 def _repr_pretty_(self):
544 def _repr_pretty_(self):
545 return self.data
545 return self.data
546
546
547
547
548 class HTML(TextDisplayObject):
548 class HTML(TextDisplayObject):
549
549
550 def _repr_html_(self):
550 def _repr_html_(self):
551 return self.data
551 return self.data
552
552
553 def __html__(self):
553 def __html__(self):
554 """
554 """
555 This method exists to inform other HTML-using modules (e.g. Markupsafe,
555 This method exists to inform other HTML-using modules (e.g. Markupsafe,
556 htmltag, etc) that this object is HTML and does not need things like
556 htmltag, etc) that this object is HTML and does not need things like
557 special characters (<>&) escaped.
557 special characters (<>&) escaped.
558 """
558 """
559 return self._repr_html_()
559 return self._repr_html_()
560
560
561
561
562 class Markdown(TextDisplayObject):
562 class Markdown(TextDisplayObject):
563
563
564 def _repr_markdown_(self):
564 def _repr_markdown_(self):
565 return self.data
565 return self.data
566
566
567
567
568 class Math(TextDisplayObject):
568 class Math(TextDisplayObject):
569
569
570 def _repr_latex_(self):
570 def _repr_latex_(self):
571 s = self.data.strip('$')
571 s = self.data.strip('$')
572 return "$$%s$$" % s
572 return "$$%s$$" % s
573
573
574
574
575 class Latex(TextDisplayObject):
575 class Latex(TextDisplayObject):
576
576
577 def _repr_latex_(self):
577 def _repr_latex_(self):
578 return self.data
578 return self.data
579
579
580
580
581 class SVG(DisplayObject):
581 class SVG(DisplayObject):
582
582
583 _read_flags = 'rb'
583 _read_flags = 'rb'
584 # wrap data in a property, which extracts the <svg> tag, discarding
584 # wrap data in a property, which extracts the <svg> tag, discarding
585 # document headers
585 # document headers
586 _data = None
586 _data = None
587
587
588 @property
588 @property
589 def data(self):
589 def data(self):
590 return self._data
590 return self._data
591
591
592 @data.setter
592 @data.setter
593 def data(self, svg):
593 def data(self, svg):
594 if svg is None:
594 if svg is None:
595 self._data = None
595 self._data = None
596 return
596 return
597 # parse into dom object
597 # parse into dom object
598 from xml.dom import minidom
598 from xml.dom import minidom
599 svg = cast_bytes_py2(svg)
599 svg = cast_bytes_py2(svg)
600 x = minidom.parseString(svg)
600 x = minidom.parseString(svg)
601 # get svg tag (should be 1)
601 # get svg tag (should be 1)
602 found_svg = x.getElementsByTagName('svg')
602 found_svg = x.getElementsByTagName('svg')
603 if found_svg:
603 if found_svg:
604 svg = found_svg[0].toxml()
604 svg = found_svg[0].toxml()
605 else:
605 else:
606 # fallback on the input, trust the user
606 # fallback on the input, trust the user
607 # but this is probably an error.
607 # but this is probably an error.
608 pass
608 pass
609 svg = cast_unicode(svg)
609 svg = cast_unicode(svg)
610 self._data = svg
610 self._data = svg
611
611
612 def _repr_svg_(self):
612 def _repr_svg_(self):
613 return self.data
613 return self.data
614
614
615
615
616 class JSON(DisplayObject):
616 class JSON(DisplayObject):
617 """JSON expects a JSON-able dict or list
617 """JSON expects a JSON-able dict or list
618
618
619 not an already-serialized JSON string.
619 not an already-serialized JSON string.
620
620
621 Scalar types (None, number, string) are not allowed, only dict or list containers.
621 Scalar types (None, number, string) are not allowed, only dict or list containers.
622 """
622 """
623 # wrap data in a property, which warns about passing already-serialized JSON
623 # wrap data in a property, which warns about passing already-serialized JSON
624 _data = None
624 _data = None
625 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
625 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None):
626 """Create a JSON display object given raw data.
626 """Create a JSON display object given raw data.
627
627
628 Parameters
628 Parameters
629 ----------
629 ----------
630 data : dict or list
630 data : dict or list
631 JSON data to display. Not an already-serialized JSON string.
631 JSON data to display. Not an already-serialized JSON string.
632 Scalar types (None, number, string) are not allowed, only dict
632 Scalar types (None, number, string) are not allowed, only dict
633 or list containers.
633 or list containers.
634 url : unicode
634 url : unicode
635 A URL to download the data from.
635 A URL to download the data from.
636 filename : unicode
636 filename : unicode
637 Path to a local file to load the data from.
637 Path to a local file to load the data from.
638 expanded : boolean
638 expanded : boolean
639 Metadata to control whether a JSON display component is expanded.
639 Metadata to control whether a JSON display component is expanded.
640 metadata: dict
640 metadata: dict
641 Specify extra metadata to attach to the json display object.
641 Specify extra metadata to attach to the json display object.
642 """
642 """
643 self.expanded = expanded
643 self.expanded = expanded
644 self.metadata = metadata
644 self.metadata = metadata
645 super(JSON, self).__init__(data=data, url=url, filename=filename)
645 super(JSON, self).__init__(data=data, url=url, filename=filename)
646
646
647 def _check_data(self):
647 def _check_data(self):
648 if self.data is not None and not isinstance(self.data, (dict, list)):
648 if self.data is not None and not isinstance(self.data, (dict, list)):
649 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
649 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
650
650
651 @property
651 @property
652 def data(self):
652 def data(self):
653 return self._data
653 return self._data
654
654
655 @data.setter
655 @data.setter
656 def data(self, data):
656 def data(self, data):
657 if isinstance(data, str):
657 if isinstance(data, str):
658 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
658 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
659 data = json.loads(data)
659 data = json.loads(data)
660 self._data = data
660 self._data = data
661
661
662 def _data_and_metadata(self):
662 def _data_and_metadata(self):
663 md = {'expanded': self.expanded}
663 md = {'expanded': self.expanded}
664 if self.metadata:
664 if self.metadata:
665 md.update(self.metadata)
665 md.update(self.metadata)
666 return self.data, md
666 return self.data, md
667
667
668 def _repr_json_(self):
668 def _repr_json_(self):
669 return self._data_and_metadata()
669 return self._data_and_metadata()
670
670
671 css_t = """$("head").append($("<link/>").attr({
671 css_t = """$("head").append($("<link/>").attr({
672 rel: "stylesheet",
672 rel: "stylesheet",
673 type: "text/css",
673 type: "text/css",
674 href: "%s"
674 href: "%s"
675 }));
675 }));
676 """
676 """
677
677
678 lib_t1 = """$.getScript("%s", function () {
678 lib_t1 = """$.getScript("%s", function () {
679 """
679 """
680 lib_t2 = """});
680 lib_t2 = """});
681 """
681 """
682
682
683 class GeoJSON(JSON):
684
685 @property
686 def data(self):
687 return self._data
688
689 @data.setter
690 def data(self, data):
691 if isinstance(data, str):
692 data = json.loads(data)
693 self._data = data
694
695 def _ipython_display_(self):
696 bundle = {
697 'application/geo+json': self.data,
698 'text/plain': '<jupyterlab_geojson.GeoJSON object>'
699 }
700 display(bundle, raw=True)
701
683 class Javascript(TextDisplayObject):
702 class Javascript(TextDisplayObject):
684
703
685 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
704 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
686 """Create a Javascript display object given raw data.
705 """Create a Javascript display object given raw data.
687
706
688 When this object is returned by an expression or passed to the
707 When this object is returned by an expression or passed to the
689 display function, it will result in the data being displayed
708 display function, it will result in the data being displayed
690 in the frontend. If the data is a URL, the data will first be
709 in the frontend. If the data is a URL, the data will first be
691 downloaded and then displayed.
710 downloaded and then displayed.
692
711
693 In the Notebook, the containing element will be available as `element`,
712 In the Notebook, the containing element will be available as `element`,
694 and jQuery will be available. Content appended to `element` will be
713 and jQuery will be available. Content appended to `element` will be
695 visible in the output area.
714 visible in the output area.
696
715
697 Parameters
716 Parameters
698 ----------
717 ----------
699 data : unicode, str or bytes
718 data : unicode, str or bytes
700 The Javascript source code or a URL to download it from.
719 The Javascript source code or a URL to download it from.
701 url : unicode
720 url : unicode
702 A URL to download the data from.
721 A URL to download the data from.
703 filename : unicode
722 filename : unicode
704 Path to a local file to load the data from.
723 Path to a local file to load the data from.
705 lib : list or str
724 lib : list or str
706 A sequence of Javascript library URLs to load asynchronously before
725 A sequence of Javascript library URLs to load asynchronously before
707 running the source code. The full URLs of the libraries should
726 running the source code. The full URLs of the libraries should
708 be given. A single Javascript library URL can also be given as a
727 be given. A single Javascript library URL can also be given as a
709 string.
728 string.
710 css: : list or str
729 css: : list or str
711 A sequence of css files to load before running the source code.
730 A sequence of css files to load before running the source code.
712 The full URLs of the css files should be given. A single css URL
731 The full URLs of the css files should be given. A single css URL
713 can also be given as a string.
732 can also be given as a string.
714 """
733 """
715 if isinstance(lib, str):
734 if isinstance(lib, str):
716 lib = [lib]
735 lib = [lib]
717 elif lib is None:
736 elif lib is None:
718 lib = []
737 lib = []
719 if isinstance(css, str):
738 if isinstance(css, str):
720 css = [css]
739 css = [css]
721 elif css is None:
740 elif css is None:
722 css = []
741 css = []
723 if not isinstance(lib, (list,tuple)):
742 if not isinstance(lib, (list,tuple)):
724 raise TypeError('expected sequence, got: %r' % lib)
743 raise TypeError('expected sequence, got: %r' % lib)
725 if not isinstance(css, (list,tuple)):
744 if not isinstance(css, (list,tuple)):
726 raise TypeError('expected sequence, got: %r' % css)
745 raise TypeError('expected sequence, got: %r' % css)
727 self.lib = lib
746 self.lib = lib
728 self.css = css
747 self.css = css
729 super(Javascript, self).__init__(data=data, url=url, filename=filename)
748 super(Javascript, self).__init__(data=data, url=url, filename=filename)
730
749
731 def _repr_javascript_(self):
750 def _repr_javascript_(self):
732 r = ''
751 r = ''
733 for c in self.css:
752 for c in self.css:
734 r += css_t % c
753 r += css_t % c
735 for l in self.lib:
754 for l in self.lib:
736 r += lib_t1 % l
755 r += lib_t1 % l
737 r += self.data
756 r += self.data
738 r += lib_t2*len(self.lib)
757 r += lib_t2*len(self.lib)
739 return r
758 return r
740
759
741 # constants for identifying png/jpeg data
760 # constants for identifying png/jpeg data
742 _PNG = b'\x89PNG\r\n\x1a\n'
761 _PNG = b'\x89PNG\r\n\x1a\n'
743 _JPEG = b'\xff\xd8'
762 _JPEG = b'\xff\xd8'
744
763
745 def _pngxy(data):
764 def _pngxy(data):
746 """read the (width, height) from a PNG header"""
765 """read the (width, height) from a PNG header"""
747 ihdr = data.index(b'IHDR')
766 ihdr = data.index(b'IHDR')
748 # next 8 bytes are width/height
767 # next 8 bytes are width/height
749 w4h4 = data[ihdr+4:ihdr+12]
768 w4h4 = data[ihdr+4:ihdr+12]
750 return struct.unpack('>ii', w4h4)
769 return struct.unpack('>ii', w4h4)
751
770
752 def _jpegxy(data):
771 def _jpegxy(data):
753 """read the (width, height) from a JPEG header"""
772 """read the (width, height) from a JPEG header"""
754 # adapted from http://www.64lines.com/jpeg-width-height
773 # adapted from http://www.64lines.com/jpeg-width-height
755
774
756 idx = 4
775 idx = 4
757 while True:
776 while True:
758 block_size = struct.unpack('>H', data[idx:idx+2])[0]
777 block_size = struct.unpack('>H', data[idx:idx+2])[0]
759 idx = idx + block_size
778 idx = idx + block_size
760 if data[idx:idx+2] == b'\xFF\xC0':
779 if data[idx:idx+2] == b'\xFF\xC0':
761 # found Start of Frame
780 # found Start of Frame
762 iSOF = idx
781 iSOF = idx
763 break
782 break
764 else:
783 else:
765 # read another block
784 # read another block
766 idx += 2
785 idx += 2
767
786
768 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
787 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
769 return w, h
788 return w, h
770
789
771 class Image(DisplayObject):
790 class Image(DisplayObject):
772
791
773 _read_flags = 'rb'
792 _read_flags = 'rb'
774 _FMT_JPEG = u'jpeg'
793 _FMT_JPEG = u'jpeg'
775 _FMT_PNG = u'png'
794 _FMT_PNG = u'png'
776 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
795 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
777
796
778 def __init__(self, data=None, url=None, filename=None, format=None,
797 def __init__(self, data=None, url=None, filename=None, format=None,
779 embed=None, width=None, height=None, retina=False,
798 embed=None, width=None, height=None, retina=False,
780 unconfined=False, metadata=None):
799 unconfined=False, metadata=None):
781 """Create a PNG/JPEG image object given raw data.
800 """Create a PNG/JPEG image object given raw data.
782
801
783 When this object is returned by an input cell or passed to the
802 When this object is returned by an input cell or passed to the
784 display function, it will result in the image being displayed
803 display function, it will result in the image being displayed
785 in the frontend.
804 in the frontend.
786
805
787 Parameters
806 Parameters
788 ----------
807 ----------
789 data : unicode, str or bytes
808 data : unicode, str or bytes
790 The raw image data or a URL or filename to load the data from.
809 The raw image data or a URL or filename to load the data from.
791 This always results in embedded image data.
810 This always results in embedded image data.
792 url : unicode
811 url : unicode
793 A URL to download the data from. If you specify `url=`,
812 A URL to download the data from. If you specify `url=`,
794 the image data will not be embedded unless you also specify `embed=True`.
813 the image data will not be embedded unless you also specify `embed=True`.
795 filename : unicode
814 filename : unicode
796 Path to a local file to load the data from.
815 Path to a local file to load the data from.
797 Images from a file are always embedded.
816 Images from a file are always embedded.
798 format : unicode
817 format : unicode
799 The format of the image data (png/jpeg/jpg). If a filename or URL is given
818 The format of the image data (png/jpeg/jpg). If a filename or URL is given
800 for format will be inferred from the filename extension.
819 for format will be inferred from the filename extension.
801 embed : bool
820 embed : bool
802 Should the image data be embedded using a data URI (True) or be
821 Should the image data be embedded using a data URI (True) or be
803 loaded using an <img> tag. Set this to True if you want the image
822 loaded using an <img> tag. Set this to True if you want the image
804 to be viewable later with no internet connection in the notebook.
823 to be viewable later with no internet connection in the notebook.
805
824
806 Default is `True`, unless the keyword argument `url` is set, then
825 Default is `True`, unless the keyword argument `url` is set, then
807 default value is `False`.
826 default value is `False`.
808
827
809 Note that QtConsole is not able to display images if `embed` is set to `False`
828 Note that QtConsole is not able to display images if `embed` is set to `False`
810 width : int
829 width : int
811 Width in pixels to which to constrain the image in html
830 Width in pixels to which to constrain the image in html
812 height : int
831 height : int
813 Height in pixels to which to constrain the image in html
832 Height in pixels to which to constrain the image in html
814 retina : bool
833 retina : bool
815 Automatically set the width and height to half of the measured
834 Automatically set the width and height to half of the measured
816 width and height.
835 width and height.
817 This only works for embedded images because it reads the width/height
836 This only works for embedded images because it reads the width/height
818 from image data.
837 from image data.
819 For non-embedded images, you can just set the desired display width
838 For non-embedded images, you can just set the desired display width
820 and height directly.
839 and height directly.
821 unconfined: bool
840 unconfined: bool
822 Set unconfined=True to disable max-width confinement of the image.
841 Set unconfined=True to disable max-width confinement of the image.
823 metadata: dict
842 metadata: dict
824 Specify extra metadata to attach to the image.
843 Specify extra metadata to attach to the image.
825
844
826 Examples
845 Examples
827 --------
846 --------
828 # embedded image data, works in qtconsole and notebook
847 # embedded image data, works in qtconsole and notebook
829 # when passed positionally, the first arg can be any of raw image data,
848 # when passed positionally, the first arg can be any of raw image data,
830 # a URL, or a filename from which to load image data.
849 # a URL, or a filename from which to load image data.
831 # The result is always embedding image data for inline images.
850 # The result is always embedding image data for inline images.
832 Image('http://www.google.fr/images/srpr/logo3w.png')
851 Image('http://www.google.fr/images/srpr/logo3w.png')
833 Image('/path/to/image.jpg')
852 Image('/path/to/image.jpg')
834 Image(b'RAW_PNG_DATA...')
853 Image(b'RAW_PNG_DATA...')
835
854
836 # Specifying Image(url=...) does not embed the image data,
855 # Specifying Image(url=...) does not embed the image data,
837 # it only generates `<img>` tag with a link to the source.
856 # it only generates `<img>` tag with a link to the source.
838 # This will not work in the qtconsole or offline.
857 # This will not work in the qtconsole or offline.
839 Image(url='http://www.google.fr/images/srpr/logo3w.png')
858 Image(url='http://www.google.fr/images/srpr/logo3w.png')
840
859
841 """
860 """
842 if filename is not None:
861 if filename is not None:
843 ext = self._find_ext(filename)
862 ext = self._find_ext(filename)
844 elif url is not None:
863 elif url is not None:
845 ext = self._find_ext(url)
864 ext = self._find_ext(url)
846 elif data is None:
865 elif data is None:
847 raise ValueError("No image data found. Expecting filename, url, or data.")
866 raise ValueError("No image data found. Expecting filename, url, or data.")
848 elif isinstance(data, str) and (
867 elif isinstance(data, str) and (
849 data.startswith('http') or _safe_exists(data)
868 data.startswith('http') or _safe_exists(data)
850 ):
869 ):
851 ext = self._find_ext(data)
870 ext = self._find_ext(data)
852 else:
871 else:
853 ext = None
872 ext = None
854
873
855 if format is None:
874 if format is None:
856 if ext is not None:
875 if ext is not None:
857 if ext == u'jpg' or ext == u'jpeg':
876 if ext == u'jpg' or ext == u'jpeg':
858 format = self._FMT_JPEG
877 format = self._FMT_JPEG
859 if ext == u'png':
878 if ext == u'png':
860 format = self._FMT_PNG
879 format = self._FMT_PNG
861 else:
880 else:
862 format = ext.lower()
881 format = ext.lower()
863 elif isinstance(data, bytes):
882 elif isinstance(data, bytes):
864 # infer image type from image data header,
883 # infer image type from image data header,
865 # only if format has not been specified.
884 # only if format has not been specified.
866 if data[:2] == _JPEG:
885 if data[:2] == _JPEG:
867 format = self._FMT_JPEG
886 format = self._FMT_JPEG
868
887
869 # failed to detect format, default png
888 # failed to detect format, default png
870 if format is None:
889 if format is None:
871 format = 'png'
890 format = 'png'
872
891
873 if format.lower() == 'jpg':
892 if format.lower() == 'jpg':
874 # jpg->jpeg
893 # jpg->jpeg
875 format = self._FMT_JPEG
894 format = self._FMT_JPEG
876
895
877 self.format = format.lower()
896 self.format = format.lower()
878 self.embed = embed if embed is not None else (url is None)
897 self.embed = embed if embed is not None else (url is None)
879
898
880 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
899 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
881 raise ValueError("Cannot embed the '%s' image format" % (self.format))
900 raise ValueError("Cannot embed the '%s' image format" % (self.format))
882 self.width = width
901 self.width = width
883 self.height = height
902 self.height = height
884 self.retina = retina
903 self.retina = retina
885 self.unconfined = unconfined
904 self.unconfined = unconfined
886 self.metadata = metadata
905 self.metadata = metadata
887 super(Image, self).__init__(data=data, url=url, filename=filename)
906 super(Image, self).__init__(data=data, url=url, filename=filename)
888
907
889 if retina:
908 if retina:
890 self._retina_shape()
909 self._retina_shape()
891
910
892 def _retina_shape(self):
911 def _retina_shape(self):
893 """load pixel-doubled width and height from image data"""
912 """load pixel-doubled width and height from image data"""
894 if not self.embed:
913 if not self.embed:
895 return
914 return
896 if self.format == 'png':
915 if self.format == 'png':
897 w, h = _pngxy(self.data)
916 w, h = _pngxy(self.data)
898 elif self.format == 'jpeg':
917 elif self.format == 'jpeg':
899 w, h = _jpegxy(self.data)
918 w, h = _jpegxy(self.data)
900 else:
919 else:
901 # retina only supports png
920 # retina only supports png
902 return
921 return
903 self.width = w // 2
922 self.width = w // 2
904 self.height = h // 2
923 self.height = h // 2
905
924
906 def reload(self):
925 def reload(self):
907 """Reload the raw data from file or URL."""
926 """Reload the raw data from file or URL."""
908 if self.embed:
927 if self.embed:
909 super(Image,self).reload()
928 super(Image,self).reload()
910 if self.retina:
929 if self.retina:
911 self._retina_shape()
930 self._retina_shape()
912
931
913 def _repr_html_(self):
932 def _repr_html_(self):
914 if not self.embed:
933 if not self.embed:
915 width = height = klass = ''
934 width = height = klass = ''
916 if self.width:
935 if self.width:
917 width = ' width="%d"' % self.width
936 width = ' width="%d"' % self.width
918 if self.height:
937 if self.height:
919 height = ' height="%d"' % self.height
938 height = ' height="%d"' % self.height
920 if self.unconfined:
939 if self.unconfined:
921 klass = ' class="unconfined"'
940 klass = ' class="unconfined"'
922 return u'<img src="{url}"{width}{height}{klass}/>'.format(
941 return u'<img src="{url}"{width}{height}{klass}/>'.format(
923 url=self.url,
942 url=self.url,
924 width=width,
943 width=width,
925 height=height,
944 height=height,
926 klass=klass,
945 klass=klass,
927 )
946 )
928
947
929 def _data_and_metadata(self):
948 def _data_and_metadata(self):
930 """shortcut for returning metadata with shape information, if defined"""
949 """shortcut for returning metadata with shape information, if defined"""
931 md = {}
950 md = {}
932 if self.width:
951 if self.width:
933 md['width'] = self.width
952 md['width'] = self.width
934 if self.height:
953 if self.height:
935 md['height'] = self.height
954 md['height'] = self.height
936 if self.unconfined:
955 if self.unconfined:
937 md['unconfined'] = self.unconfined
956 md['unconfined'] = self.unconfined
938 if self.metadata:
957 if self.metadata:
939 md.update(self.metadata)
958 md.update(self.metadata)
940 if md:
959 if md:
941 return self.data, md
960 return self.data, md
942 else:
961 else:
943 return self.data
962 return self.data
944
963
945 def _repr_png_(self):
964 def _repr_png_(self):
946 if self.embed and self.format == u'png':
965 if self.embed and self.format == u'png':
947 return self._data_and_metadata()
966 return self._data_and_metadata()
948
967
949 def _repr_jpeg_(self):
968 def _repr_jpeg_(self):
950 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
969 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
951 return self._data_and_metadata()
970 return self._data_and_metadata()
952
971
953 def _find_ext(self, s):
972 def _find_ext(self, s):
954 return s.split('.')[-1].lower()
973 return s.split('.')[-1].lower()
955
974
956 class Video(DisplayObject):
975 class Video(DisplayObject):
957
976
958 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
977 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
959 """Create a video object given raw data or an URL.
978 """Create a video object given raw data or an URL.
960
979
961 When this object is returned by an input cell or passed to the
980 When this object is returned by an input cell or passed to the
962 display function, it will result in the video being displayed
981 display function, it will result in the video being displayed
963 in the frontend.
982 in the frontend.
964
983
965 Parameters
984 Parameters
966 ----------
985 ----------
967 data : unicode, str or bytes
986 data : unicode, str or bytes
968 The raw video data or a URL or filename to load the data from.
987 The raw video data or a URL or filename to load the data from.
969 Raw data will require passing `embed=True`.
988 Raw data will require passing `embed=True`.
970 url : unicode
989 url : unicode
971 A URL for the video. If you specify `url=`,
990 A URL for the video. If you specify `url=`,
972 the image data will not be embedded.
991 the image data will not be embedded.
973 filename : unicode
992 filename : unicode
974 Path to a local file containing the video.
993 Path to a local file containing the video.
975 Will be interpreted as a local URL unless `embed=True`.
994 Will be interpreted as a local URL unless `embed=True`.
976 embed : bool
995 embed : bool
977 Should the video be embedded using a data URI (True) or be
996 Should the video be embedded using a data URI (True) or be
978 loaded using a <video> tag (False).
997 loaded using a <video> tag (False).
979
998
980 Since videos are large, embedding them should be avoided, if possible.
999 Since videos are large, embedding them should be avoided, if possible.
981 You must confirm embedding as your intention by passing `embed=True`.
1000 You must confirm embedding as your intention by passing `embed=True`.
982
1001
983 Local files can be displayed with URLs without embedding the content, via::
1002 Local files can be displayed with URLs without embedding the content, via::
984
1003
985 Video('./video.mp4')
1004 Video('./video.mp4')
986
1005
987 mimetype: unicode
1006 mimetype: unicode
988 Specify the mimetype for embedded videos.
1007 Specify the mimetype for embedded videos.
989 Default will be guessed from file extension, if available.
1008 Default will be guessed from file extension, if available.
990
1009
991 Examples
1010 Examples
992 --------
1011 --------
993
1012
994 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
1013 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
995 Video('path/to/video.mp4')
1014 Video('path/to/video.mp4')
996 Video('path/to/video.mp4', embed=True)
1015 Video('path/to/video.mp4', embed=True)
997 Video(b'raw-videodata', embed=True)
1016 Video(b'raw-videodata', embed=True)
998 """
1017 """
999 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1018 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1000 url = data
1019 url = data
1001 data = None
1020 data = None
1002 elif os.path.exists(data):
1021 elif os.path.exists(data):
1003 filename = data
1022 filename = data
1004 data = None
1023 data = None
1005
1024
1006 if data and not embed:
1025 if data and not embed:
1007 msg = ''.join([
1026 msg = ''.join([
1008 "To embed videos, you must pass embed=True ",
1027 "To embed videos, you must pass embed=True ",
1009 "(this may make your notebook files huge)\n",
1028 "(this may make your notebook files huge)\n",
1010 "Consider passing Video(url='...')",
1029 "Consider passing Video(url='...')",
1011 ])
1030 ])
1012 raise ValueError(msg)
1031 raise ValueError(msg)
1013
1032
1014 self.mimetype = mimetype
1033 self.mimetype = mimetype
1015 self.embed = embed
1034 self.embed = embed
1016 super(Video, self).__init__(data=data, url=url, filename=filename)
1035 super(Video, self).__init__(data=data, url=url, filename=filename)
1017
1036
1018 def _repr_html_(self):
1037 def _repr_html_(self):
1019 # External URLs and potentially local files are not embedded into the
1038 # External URLs and potentially local files are not embedded into the
1020 # notebook output.
1039 # notebook output.
1021 if not self.embed:
1040 if not self.embed:
1022 url = self.url if self.url is not None else self.filename
1041 url = self.url if self.url is not None else self.filename
1023 output = """<video src="{0}" controls>
1042 output = """<video src="{0}" controls>
1024 Your browser does not support the <code>video</code> element.
1043 Your browser does not support the <code>video</code> element.
1025 </video>""".format(url)
1044 </video>""".format(url)
1026 return output
1045 return output
1027
1046
1028 # Embedded videos are base64-encoded.
1047 # Embedded videos are base64-encoded.
1029 mimetype = self.mimetype
1048 mimetype = self.mimetype
1030 if self.filename is not None:
1049 if self.filename is not None:
1031 if not mimetype:
1050 if not mimetype:
1032 mimetype, _ = mimetypes.guess_type(self.filename)
1051 mimetype, _ = mimetypes.guess_type(self.filename)
1033
1052
1034 with open(self.filename, 'rb') as f:
1053 with open(self.filename, 'rb') as f:
1035 video = f.read()
1054 video = f.read()
1036 else:
1055 else:
1037 video = self.data
1056 video = self.data
1038 if isinstance(video, str):
1057 if isinstance(video, str):
1039 # unicode input is already b64-encoded
1058 # unicode input is already b64-encoded
1040 b64_video = video
1059 b64_video = video
1041 else:
1060 else:
1042 b64_video = base64_encode(video).decode('ascii').rstrip()
1061 b64_video = base64_encode(video).decode('ascii').rstrip()
1043
1062
1044 output = """<video controls>
1063 output = """<video controls>
1045 <source src="data:{0};base64,{1}" type="{0}">
1064 <source src="data:{0};base64,{1}" type="{0}">
1046 Your browser does not support the video tag.
1065 Your browser does not support the video tag.
1047 </video>""".format(mimetype, b64_video)
1066 </video>""".format(mimetype, b64_video)
1048 return output
1067 return output
1049
1068
1050 def reload(self):
1069 def reload(self):
1051 # TODO
1070 # TODO
1052 pass
1071 pass
1053
1072
1054 def _repr_png_(self):
1073 def _repr_png_(self):
1055 # TODO
1074 # TODO
1056 pass
1075 pass
1057 def _repr_jpeg_(self):
1076 def _repr_jpeg_(self):
1058 # TODO
1077 # TODO
1059 pass
1078 pass
1060
1079
1061 def clear_output(wait=False):
1080 def clear_output(wait=False):
1062 """Clear the output of the current cell receiving output.
1081 """Clear the output of the current cell receiving output.
1063
1082
1064 Parameters
1083 Parameters
1065 ----------
1084 ----------
1066 wait : bool [default: false]
1085 wait : bool [default: false]
1067 Wait to clear the output until new output is available to replace it."""
1086 Wait to clear the output until new output is available to replace it."""
1068 from IPython.core.interactiveshell import InteractiveShell
1087 from IPython.core.interactiveshell import InteractiveShell
1069 if InteractiveShell.initialized():
1088 if InteractiveShell.initialized():
1070 InteractiveShell.instance().display_pub.clear_output(wait)
1089 InteractiveShell.instance().display_pub.clear_output(wait)
1071 else:
1090 else:
1072 print('\033[2K\r', end='')
1091 print('\033[2K\r', end='')
1073 sys.stdout.flush()
1092 sys.stdout.flush()
1074 print('\033[2K\r', end='')
1093 print('\033[2K\r', end='')
1075 sys.stderr.flush()
1094 sys.stderr.flush()
1076
1095
1077
1096
1078 @skip_doctest
1097 @skip_doctest
1079 def set_matplotlib_formats(*formats, **kwargs):
1098 def set_matplotlib_formats(*formats, **kwargs):
1080 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1099 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1081
1100
1082 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1101 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1083
1102
1084 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1103 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1085
1104
1086 To set this in your config files use the following::
1105 To set this in your config files use the following::
1087
1106
1088 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1107 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1089 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1108 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1090
1109
1091 Parameters
1110 Parameters
1092 ----------
1111 ----------
1093 *formats : strs
1112 *formats : strs
1094 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1113 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1095 **kwargs :
1114 **kwargs :
1096 Keyword args will be relayed to ``figure.canvas.print_figure``.
1115 Keyword args will be relayed to ``figure.canvas.print_figure``.
1097 """
1116 """
1098 from IPython.core.interactiveshell import InteractiveShell
1117 from IPython.core.interactiveshell import InteractiveShell
1099 from IPython.core.pylabtools import select_figure_formats
1118 from IPython.core.pylabtools import select_figure_formats
1100 # build kwargs, starting with InlineBackend config
1119 # build kwargs, starting with InlineBackend config
1101 kw = {}
1120 kw = {}
1102 from ipykernel.pylab.config import InlineBackend
1121 from ipykernel.pylab.config import InlineBackend
1103 cfg = InlineBackend.instance()
1122 cfg = InlineBackend.instance()
1104 kw.update(cfg.print_figure_kwargs)
1123 kw.update(cfg.print_figure_kwargs)
1105 kw.update(**kwargs)
1124 kw.update(**kwargs)
1106 shell = InteractiveShell.instance()
1125 shell = InteractiveShell.instance()
1107 select_figure_formats(shell, formats, **kw)
1126 select_figure_formats(shell, formats, **kw)
1108
1127
1109 @skip_doctest
1128 @skip_doctest
1110 def set_matplotlib_close(close=True):
1129 def set_matplotlib_close(close=True):
1111 """Set whether the inline backend closes all figures automatically or not.
1130 """Set whether the inline backend closes all figures automatically or not.
1112
1131
1113 By default, the inline backend used in the IPython Notebook will close all
1132 By default, the inline backend used in the IPython Notebook will close all
1114 matplotlib figures automatically after each cell is run. This means that
1133 matplotlib figures automatically after each cell is run. This means that
1115 plots in different cells won't interfere. Sometimes, you may want to make
1134 plots in different cells won't interfere. Sometimes, you may want to make
1116 a plot in one cell and then refine it in later cells. This can be accomplished
1135 a plot in one cell and then refine it in later cells. This can be accomplished
1117 by::
1136 by::
1118
1137
1119 In [1]: set_matplotlib_close(False)
1138 In [1]: set_matplotlib_close(False)
1120
1139
1121 To set this in your config files use the following::
1140 To set this in your config files use the following::
1122
1141
1123 c.InlineBackend.close_figures = False
1142 c.InlineBackend.close_figures = False
1124
1143
1125 Parameters
1144 Parameters
1126 ----------
1145 ----------
1127 close : bool
1146 close : bool
1128 Should all matplotlib figures be automatically closed after each cell is
1147 Should all matplotlib figures be automatically closed after each cell is
1129 run?
1148 run?
1130 """
1149 """
1131 from ipykernel.pylab.config import InlineBackend
1150 from ipykernel.pylab.config import InlineBackend
1132 cfg = InlineBackend.instance()
1151 cfg = InlineBackend.instance()
1133 cfg.close_figures = close
1152 cfg.close_figures = close
General Comments 0
You need to be logged in to leave comments. Login now