##// END OF EJS Templates
check image header to identify image type,...
MinRK -
Show More
@@ -1,557 +1,565 b''
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 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from __future__ import print_function
20 from __future__ import print_function
21
21
22 from .displaypub import (
22 from .displaypub import (
23 publish_pretty, publish_html,
23 publish_pretty, publish_html,
24 publish_latex, publish_svg,
24 publish_latex, publish_svg,
25 publish_png, publish_json,
25 publish_png, publish_json,
26 publish_javascript, publish_jpeg
26 publish_javascript, publish_jpeg
27 )
27 )
28
28
29 from IPython.utils.py3compat import string_types
29 from IPython.utils.py3compat import string_types
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Main functions
32 # Main functions
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 def display(*objs, **kwargs):
35 def display(*objs, **kwargs):
36 """Display a Python object in all frontends.
36 """Display a Python object in all frontends.
37
37
38 By default all representations will be computed and sent to the frontends.
38 By default all representations will be computed and sent to the frontends.
39 Frontends can decide which representation is used and how.
39 Frontends can decide which representation is used and how.
40
40
41 Parameters
41 Parameters
42 ----------
42 ----------
43 objs : tuple of objects
43 objs : tuple of objects
44 The Python objects to display.
44 The Python objects to display.
45 include : list or tuple, optional
45 include : list or tuple, optional
46 A list of format type strings (MIME types) to include in the
46 A list of format type strings (MIME types) to include in the
47 format data dict. If this is set *only* the format types included
47 format data dict. If this is set *only* the format types included
48 in this list will be computed.
48 in this list will be computed.
49 exclude : list or tuple, optional
49 exclude : list or tuple, optional
50 A list of format type string (MIME types) to exclue in the format
50 A list of format type string (MIME types) to exclue in the format
51 data dict. If this is set all format types will be computed,
51 data dict. If this is set all format types will be computed,
52 except for those included in this argument.
52 except for those included in this argument.
53 """
53 """
54 include = kwargs.get('include')
54 include = kwargs.get('include')
55 exclude = kwargs.get('exclude')
55 exclude = kwargs.get('exclude')
56
56
57 from IPython.core.interactiveshell import InteractiveShell
57 from IPython.core.interactiveshell import InteractiveShell
58 inst = InteractiveShell.instance()
58 inst = InteractiveShell.instance()
59 format = inst.display_formatter.format
59 format = inst.display_formatter.format
60 publish = inst.display_pub.publish
60 publish = inst.display_pub.publish
61
61
62 for obj in objs:
62 for obj in objs:
63 format_dict = format(obj, include=include, exclude=exclude)
63 format_dict = format(obj, include=include, exclude=exclude)
64 publish('IPython.core.display.display', format_dict)
64 publish('IPython.core.display.display', format_dict)
65
65
66
66
67 def display_pretty(*objs, **kwargs):
67 def display_pretty(*objs, **kwargs):
68 """Display the pretty (default) representation of an object.
68 """Display the pretty (default) representation of an object.
69
69
70 Parameters
70 Parameters
71 ----------
71 ----------
72 objs : tuple of objects
72 objs : tuple of objects
73 The Python objects to display, or if raw=True raw text data to
73 The Python objects to display, or if raw=True raw text data to
74 display.
74 display.
75 raw : bool
75 raw : bool
76 Are the data objects raw data or Python objects that need to be
76 Are the data objects raw data or Python objects that need to be
77 formatted before display? [default: False]
77 formatted before display? [default: False]
78 """
78 """
79 raw = kwargs.pop('raw',False)
79 raw = kwargs.pop('raw',False)
80 if raw:
80 if raw:
81 for obj in objs:
81 for obj in objs:
82 publish_pretty(obj)
82 publish_pretty(obj)
83 else:
83 else:
84 display(*objs, include=['text/plain'])
84 display(*objs, include=['text/plain'])
85
85
86
86
87 def display_html(*objs, **kwargs):
87 def display_html(*objs, **kwargs):
88 """Display the HTML representation of an object.
88 """Display the HTML representation of an object.
89
89
90 Parameters
90 Parameters
91 ----------
91 ----------
92 objs : tuple of objects
92 objs : tuple of objects
93 The Python objects to display, or if raw=True raw HTML data to
93 The Python objects to display, or if raw=True raw HTML data to
94 display.
94 display.
95 raw : bool
95 raw : bool
96 Are the data objects raw data or Python objects that need to be
96 Are the data objects raw data or Python objects that need to be
97 formatted before display? [default: False]
97 formatted before display? [default: False]
98 """
98 """
99 raw = kwargs.pop('raw',False)
99 raw = kwargs.pop('raw',False)
100 if raw:
100 if raw:
101 for obj in objs:
101 for obj in objs:
102 publish_html(obj)
102 publish_html(obj)
103 else:
103 else:
104 display(*objs, include=['text/plain','text/html'])
104 display(*objs, include=['text/plain','text/html'])
105
105
106
106
107 def display_svg(*objs, **kwargs):
107 def display_svg(*objs, **kwargs):
108 """Display the SVG representation of an object.
108 """Display the SVG representation of an object.
109
109
110 Parameters
110 Parameters
111 ----------
111 ----------
112 objs : tuple of objects
112 objs : tuple of objects
113 The Python objects to display, or if raw=True raw svg data to
113 The Python objects to display, or if raw=True raw svg data to
114 display.
114 display.
115 raw : bool
115 raw : bool
116 Are the data objects raw data or Python objects that need to be
116 Are the data objects raw data or Python objects that need to be
117 formatted before display? [default: False]
117 formatted before display? [default: False]
118 """
118 """
119 raw = kwargs.pop('raw',False)
119 raw = kwargs.pop('raw',False)
120 if raw:
120 if raw:
121 for obj in objs:
121 for obj in objs:
122 publish_svg(obj)
122 publish_svg(obj)
123 else:
123 else:
124 display(*objs, include=['text/plain','image/svg+xml'])
124 display(*objs, include=['text/plain','image/svg+xml'])
125
125
126
126
127 def display_png(*objs, **kwargs):
127 def display_png(*objs, **kwargs):
128 """Display the PNG representation of an object.
128 """Display the PNG representation of an object.
129
129
130 Parameters
130 Parameters
131 ----------
131 ----------
132 objs : tuple of objects
132 objs : tuple of objects
133 The Python objects to display, or if raw=True raw png data to
133 The Python objects to display, or if raw=True raw png data to
134 display.
134 display.
135 raw : bool
135 raw : bool
136 Are the data objects raw data or Python objects that need to be
136 Are the data objects raw data or Python objects that need to be
137 formatted before display? [default: False]
137 formatted before display? [default: False]
138 """
138 """
139 raw = kwargs.pop('raw',False)
139 raw = kwargs.pop('raw',False)
140 if raw:
140 if raw:
141 for obj in objs:
141 for obj in objs:
142 publish_png(obj)
142 publish_png(obj)
143 else:
143 else:
144 display(*objs, include=['text/plain','image/png'])
144 display(*objs, include=['text/plain','image/png'])
145
145
146
146
147 def display_jpeg(*objs, **kwargs):
147 def display_jpeg(*objs, **kwargs):
148 """Display the JPEG representation of an object.
148 """Display the JPEG representation of an object.
149
149
150 Parameters
150 Parameters
151 ----------
151 ----------
152 objs : tuple of objects
152 objs : tuple of objects
153 The Python objects to display, or if raw=True raw JPEG data to
153 The Python objects to display, or if raw=True raw JPEG data to
154 display.
154 display.
155 raw : bool
155 raw : bool
156 Are the data objects raw data or Python objects that need to be
156 Are the data objects raw data or Python objects that need to be
157 formatted before display? [default: False]
157 formatted before display? [default: False]
158 """
158 """
159 raw = kwargs.pop('raw',False)
159 raw = kwargs.pop('raw',False)
160 if raw:
160 if raw:
161 for obj in objs:
161 for obj in objs:
162 publish_jpeg(obj)
162 publish_jpeg(obj)
163 else:
163 else:
164 display(*objs, include=['text/plain','image/jpeg'])
164 display(*objs, include=['text/plain','image/jpeg'])
165
165
166
166
167 def display_latex(*objs, **kwargs):
167 def display_latex(*objs, **kwargs):
168 """Display the LaTeX representation of an object.
168 """Display the LaTeX representation of an object.
169
169
170 Parameters
170 Parameters
171 ----------
171 ----------
172 objs : tuple of objects
172 objs : tuple of objects
173 The Python objects to display, or if raw=True raw latex data to
173 The Python objects to display, or if raw=True raw latex data to
174 display.
174 display.
175 raw : bool
175 raw : bool
176 Are the data objects raw data or Python objects that need to be
176 Are the data objects raw data or Python objects that need to be
177 formatted before display? [default: False]
177 formatted before display? [default: False]
178 """
178 """
179 raw = kwargs.pop('raw',False)
179 raw = kwargs.pop('raw',False)
180 if raw:
180 if raw:
181 for obj in objs:
181 for obj in objs:
182 publish_latex(obj)
182 publish_latex(obj)
183 else:
183 else:
184 display(*objs, include=['text/plain','text/latex'])
184 display(*objs, include=['text/plain','text/latex'])
185
185
186
186
187 def display_json(*objs, **kwargs):
187 def display_json(*objs, **kwargs):
188 """Display the JSON representation of an object.
188 """Display the JSON representation of an object.
189
189
190 Note that not many frontends support displaying JSON.
190 Note that not many frontends support displaying JSON.
191
191
192 Parameters
192 Parameters
193 ----------
193 ----------
194 objs : tuple of objects
194 objs : tuple of objects
195 The Python objects to display, or if raw=True raw json data to
195 The Python objects to display, or if raw=True raw json data to
196 display.
196 display.
197 raw : bool
197 raw : bool
198 Are the data objects raw data or Python objects that need to be
198 Are the data objects raw data or Python objects that need to be
199 formatted before display? [default: False]
199 formatted before display? [default: False]
200 """
200 """
201 raw = kwargs.pop('raw',False)
201 raw = kwargs.pop('raw',False)
202 if raw:
202 if raw:
203 for obj in objs:
203 for obj in objs:
204 publish_json(obj)
204 publish_json(obj)
205 else:
205 else:
206 display(*objs, include=['text/plain','application/json'])
206 display(*objs, include=['text/plain','application/json'])
207
207
208
208
209 def display_javascript(*objs, **kwargs):
209 def display_javascript(*objs, **kwargs):
210 """Display the Javascript representation of an object.
210 """Display the Javascript representation of an object.
211
211
212 Parameters
212 Parameters
213 ----------
213 ----------
214 objs : tuple of objects
214 objs : tuple of objects
215 The Python objects to display, or if raw=True raw javascript data to
215 The Python objects to display, or if raw=True raw javascript data to
216 display.
216 display.
217 raw : bool
217 raw : bool
218 Are the data objects raw data or Python objects that need to be
218 Are the data objects raw data or Python objects that need to be
219 formatted before display? [default: False]
219 formatted before display? [default: False]
220 """
220 """
221 raw = kwargs.pop('raw',False)
221 raw = kwargs.pop('raw',False)
222 if raw:
222 if raw:
223 for obj in objs:
223 for obj in objs:
224 publish_javascript(obj)
224 publish_javascript(obj)
225 else:
225 else:
226 display(*objs, include=['text/plain','application/javascript'])
226 display(*objs, include=['text/plain','application/javascript'])
227
227
228 #-----------------------------------------------------------------------------
228 #-----------------------------------------------------------------------------
229 # Smart classes
229 # Smart classes
230 #-----------------------------------------------------------------------------
230 #-----------------------------------------------------------------------------
231
231
232
232
233 class DisplayObject(object):
233 class DisplayObject(object):
234 """An object that wraps data to be displayed."""
234 """An object that wraps data to be displayed."""
235
235
236 _read_flags = 'r'
236 _read_flags = 'r'
237
237
238 def __init__(self, data=None, url=None, filename=None):
238 def __init__(self, data=None, url=None, filename=None):
239 """Create a display object given raw data.
239 """Create a display object given raw data.
240
240
241 When this object is returned by an expression or passed to the
241 When this object is returned by an expression or passed to the
242 display function, it will result in the data being displayed
242 display function, it will result in the data being displayed
243 in the frontend. The MIME type of the data should match the
243 in the frontend. The MIME type of the data should match the
244 subclasses used, so the Png subclass should be used for 'image/png'
244 subclasses used, so the Png subclass should be used for 'image/png'
245 data. If the data is a URL, the data will first be downloaded
245 data. If the data is a URL, the data will first be downloaded
246 and then displayed. If
246 and then displayed. If
247
247
248 Parameters
248 Parameters
249 ----------
249 ----------
250 data : unicode, str or bytes
250 data : unicode, str or bytes
251 The raw data or a URL to download the data from.
251 The raw data or a URL to download the data from.
252 url : unicode
252 url : unicode
253 A URL to download the data from.
253 A URL to download the data from.
254 filename : unicode
254 filename : unicode
255 Path to a local file to load the data from.
255 Path to a local file to load the data from.
256 """
256 """
257 if data is not None and isinstance(data, string_types) and data.startswith('http'):
257 if data is not None and isinstance(data, string_types) and data.startswith('http'):
258 self.url = data
258 self.url = data
259 self.filename = None
259 self.filename = None
260 self.data = None
260 self.data = None
261 else:
261 else:
262 self.data = data
262 self.data = data
263 self.url = url
263 self.url = url
264 self.filename = None if filename is None else unicode(filename)
264 self.filename = None if filename is None else unicode(filename)
265 self.reload()
265 self.reload()
266
266
267 def reload(self):
267 def reload(self):
268 """Reload the raw data from file or URL."""
268 """Reload the raw data from file or URL."""
269 if self.filename is not None:
269 if self.filename is not None:
270 with open(self.filename, self._read_flags) as f:
270 with open(self.filename, self._read_flags) as f:
271 self.data = f.read()
271 self.data = f.read()
272 elif self.url is not None:
272 elif self.url is not None:
273 try:
273 try:
274 import urllib2
274 import urllib2
275 response = urllib2.urlopen(self.url)
275 response = urllib2.urlopen(self.url)
276 self.data = response.read()
276 self.data = response.read()
277 # extract encoding from header, if there is one:
277 # extract encoding from header, if there is one:
278 encoding = None
278 encoding = None
279 for sub in response.headers['content-type'].split(';'):
279 for sub in response.headers['content-type'].split(';'):
280 sub = sub.strip()
280 sub = sub.strip()
281 if sub.startswith('charset'):
281 if sub.startswith('charset'):
282 encoding = sub.split('=')[-1].strip()
282 encoding = sub.split('=')[-1].strip()
283 break
283 break
284 # decode data, if an encoding was specified
284 # decode data, if an encoding was specified
285 if encoding:
285 if encoding:
286 self.data = self.data.decode(encoding, 'replace')
286 self.data = self.data.decode(encoding, 'replace')
287 except:
287 except:
288 self.data = None
288 self.data = None
289
289
290 class Pretty(DisplayObject):
290 class Pretty(DisplayObject):
291
291
292 def _repr_pretty_(self):
292 def _repr_pretty_(self):
293 return self.data
293 return self.data
294
294
295
295
296 class HTML(DisplayObject):
296 class HTML(DisplayObject):
297
297
298 def _repr_html_(self):
298 def _repr_html_(self):
299 return self.data
299 return self.data
300
300
301
301
302 class Math(DisplayObject):
302 class Math(DisplayObject):
303
303
304 def _repr_latex_(self):
304 def _repr_latex_(self):
305 s = self.data.strip('$')
305 s = self.data.strip('$')
306 return "$$%s$$" % s
306 return "$$%s$$" % s
307
307
308
308
309 class Latex(DisplayObject):
309 class Latex(DisplayObject):
310
310
311 def _repr_latex_(self):
311 def _repr_latex_(self):
312 return self.data
312 return self.data
313
313
314
314
315 class SVG(DisplayObject):
315 class SVG(DisplayObject):
316
316
317 # wrap data in a property, which extracts the <svg> tag, discarding
317 # wrap data in a property, which extracts the <svg> tag, discarding
318 # document headers
318 # document headers
319 _data = None
319 _data = None
320
320
321 @property
321 @property
322 def data(self):
322 def data(self):
323 return self._data
323 return self._data
324
324
325 @data.setter
325 @data.setter
326 def data(self, svg):
326 def data(self, svg):
327 if svg is None:
327 if svg is None:
328 self._data = None
328 self._data = None
329 return
329 return
330 # parse into dom object
330 # parse into dom object
331 from xml.dom import minidom
331 from xml.dom import minidom
332 x = minidom.parseString(svg)
332 x = minidom.parseString(svg)
333 # get svg tag (should be 1)
333 # get svg tag (should be 1)
334 found_svg = x.getElementsByTagName('svg')
334 found_svg = x.getElementsByTagName('svg')
335 if found_svg:
335 if found_svg:
336 svg = found_svg[0].toxml()
336 svg = found_svg[0].toxml()
337 else:
337 else:
338 # fallback on the input, trust the user
338 # fallback on the input, trust the user
339 # but this is probably an error.
339 # but this is probably an error.
340 pass
340 pass
341 self._data = svg
341 self._data = svg
342
342
343 def _repr_svg_(self):
343 def _repr_svg_(self):
344 return self.data
344 return self.data
345
345
346
346
347 class JSON(DisplayObject):
347 class JSON(DisplayObject):
348
348
349 def _repr_json_(self):
349 def _repr_json_(self):
350 return self.data
350 return self.data
351
351
352 css_t = """$("head").append($("<link/>").attr({
352 css_t = """$("head").append($("<link/>").attr({
353 rel: "stylesheet",
353 rel: "stylesheet",
354 type: "text/css",
354 type: "text/css",
355 href: "%s"
355 href: "%s"
356 }));
356 }));
357 """
357 """
358
358
359 lib_t1 = """$.getScript("%s", function () {
359 lib_t1 = """$.getScript("%s", function () {
360 """
360 """
361 lib_t2 = """});
361 lib_t2 = """});
362 """
362 """
363
363
364 class Javascript(DisplayObject):
364 class Javascript(DisplayObject):
365
365
366 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
366 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
367 """Create a Javascript display object given raw data.
367 """Create a Javascript display object given raw data.
368
368
369 When this object is returned by an expression or passed to the
369 When this object is returned by an expression or passed to the
370 display function, it will result in the data being displayed
370 display function, it will result in the data being displayed
371 in the frontend. If the data is a URL, the data will first be
371 in the frontend. If the data is a URL, the data will first be
372 downloaded and then displayed.
372 downloaded and then displayed.
373
373
374 In the Notebook, the containing element will be available as `element`,
374 In the Notebook, the containing element will be available as `element`,
375 and jQuery will be available. The output area starts hidden, so if
375 and jQuery will be available. The output area starts hidden, so if
376 the js appends content to `element` that should be visible, then
376 the js appends content to `element` that should be visible, then
377 it must call `container.show()` to unhide the area.
377 it must call `container.show()` to unhide the area.
378
378
379 Parameters
379 Parameters
380 ----------
380 ----------
381 data : unicode, str or bytes
381 data : unicode, str or bytes
382 The Javascript source code or a URL to download it from.
382 The Javascript source code or a URL to download it from.
383 url : unicode
383 url : unicode
384 A URL to download the data from.
384 A URL to download the data from.
385 filename : unicode
385 filename : unicode
386 Path to a local file to load the data from.
386 Path to a local file to load the data from.
387 lib : list or str
387 lib : list or str
388 A sequence of Javascript library URLs to load asynchronously before
388 A sequence of Javascript library URLs to load asynchronously before
389 running the source code. The full URLs of the libraries should
389 running the source code. The full URLs of the libraries should
390 be given. A single Javascript library URL can also be given as a
390 be given. A single Javascript library URL can also be given as a
391 string.
391 string.
392 css: : list or str
392 css: : list or str
393 A sequence of css files to load before running the source code.
393 A sequence of css files to load before running the source code.
394 The full URLs of the css files should be give. A single css URL
394 The full URLs of the css files should be give. A single css URL
395 can also be given as a string.
395 can also be given as a string.
396 """
396 """
397 if isinstance(lib, basestring):
397 if isinstance(lib, basestring):
398 lib = [lib]
398 lib = [lib]
399 elif lib is None:
399 elif lib is None:
400 lib = []
400 lib = []
401 if isinstance(css, basestring):
401 if isinstance(css, basestring):
402 css = [css]
402 css = [css]
403 elif css is None:
403 elif css is None:
404 css = []
404 css = []
405 if not isinstance(lib, (list,tuple)):
405 if not isinstance(lib, (list,tuple)):
406 raise TypeError('expected sequence, got: %r' % lib)
406 raise TypeError('expected sequence, got: %r' % lib)
407 if not isinstance(css, (list,tuple)):
407 if not isinstance(css, (list,tuple)):
408 raise TypeError('expected sequence, got: %r' % css)
408 raise TypeError('expected sequence, got: %r' % css)
409 self.lib = lib
409 self.lib = lib
410 self.css = css
410 self.css = css
411 super(Javascript, self).__init__(data=data, url=url, filename=filename)
411 super(Javascript, self).__init__(data=data, url=url, filename=filename)
412
412
413 def _repr_javascript_(self):
413 def _repr_javascript_(self):
414 r = ''
414 r = ''
415 for c in self.css:
415 for c in self.css:
416 r += css_t % c
416 r += css_t % c
417 for l in self.lib:
417 for l in self.lib:
418 r += lib_t1 % l
418 r += lib_t1 % l
419 r += self.data
419 r += self.data
420 r += lib_t2*len(self.lib)
420 r += lib_t2*len(self.lib)
421 return r
421 return r
422
422
423 # constants for identifying png/jpeg data
424 _PNG = b'\x89PNG\r\n\x1a\n'
425 _JPEG = b'\xff\xd8'
423
426
424 class Image(DisplayObject):
427 class Image(DisplayObject):
425
428
426 _read_flags = 'rb'
429 _read_flags = 'rb'
427 _FMT_JPEG = u'jpeg'
430 _FMT_JPEG = u'jpeg'
428 _FMT_PNG = u'png'
431 _FMT_PNG = u'png'
429 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
432 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
430
433
431 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
434 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
432 """Create a display an PNG/JPEG image given raw data.
435 """Create a display an PNG/JPEG image given raw data.
433
436
434 When this object is returned by an expression or passed to the
437 When this object is returned by an expression or passed to the
435 display function, it will result in the image being displayed
438 display function, it will result in the image being displayed
436 in the frontend.
439 in the frontend.
437
440
438 Parameters
441 Parameters
439 ----------
442 ----------
440 data : unicode, str or bytes
443 data : unicode, str or bytes
441 The raw data or a URL to download the data from.
444 The raw data or a URL to download the data from.
442 url : unicode
445 url : unicode
443 A URL to download the data from.
446 A URL to download the data from.
444 filename : unicode
447 filename : unicode
445 Path to a local file to load the data from.
448 Path to a local file to load the data from.
446 format : unicode
449 format : unicode
447 The format of the image data (png/jpeg/jpg). If a filename or URL is given
450 The format of the image data (png/jpeg/jpg). If a filename or URL is given
448 for format will be inferred from the filename extension.
451 for format will be inferred from the filename extension.
449 embed : bool
452 embed : bool
450 Should the image data be embedded using a data URI (True) or be
453 Should the image data be embedded using a data URI (True) or be
451 loaded using an <img> tag. Set this to True if you want the image
454 loaded using an <img> tag. Set this to True if you want the image
452 to be viewable later with no internet connection in the notebook.
455 to be viewable later with no internet connection in the notebook.
453
456
454 Default is `True`, unless the keyword argument `url` is set, then
457 Default is `True`, unless the keyword argument `url` is set, then
455 default value is `False`.
458 default value is `False`.
456
459
457 Note that QtConsole is not able to display images if `embed` is set to `False`
460 Note that QtConsole is not able to display images if `embed` is set to `False`
458 width : int
461 width : int
459 Width to which to constrain the image in html
462 Width to which to constrain the image in html
460 height : int
463 height : int
461 Height to which to constrain the image in html
464 Height to which to constrain the image in html
462
465
463 Examples
466 Examples
464 --------
467 --------
465 # embed implicitly True, works in qtconsole and notebook
468 # embed implicitly True, works in qtconsole and notebook
466 Image('http://www.google.fr/images/srpr/logo3w.png')
469 Image('http://www.google.fr/images/srpr/logo3w.png')
467
470
468 # embed implicitly False, does not works in qtconsole but works in notebook if
471 # embed implicitly False, does not works in qtconsole but works in notebook if
469 # internet connection available
472 # internet connection available
470 Image(url='http://www.google.fr/images/srpr/logo3w.png')
473 Image(url='http://www.google.fr/images/srpr/logo3w.png')
471
474
472 """
475 """
473 if filename is not None:
476 if filename is not None:
474 ext = self._find_ext(filename)
477 ext = self._find_ext(filename)
475 elif url is not None:
478 elif url is not None:
476 ext = self._find_ext(url)
479 ext = self._find_ext(url)
477 elif data is None:
480 elif data is None:
478 raise ValueError("No image data found. Expecting filename, url, or data.")
481 raise ValueError("No image data found. Expecting filename, url, or data.")
479 elif isinstance(data, string_types) and data.startswith('http'):
482 elif isinstance(data, string_types) and data.startswith('http'):
480 ext = self._find_ext(data)
483 ext = self._find_ext(data)
481 else:
484 else:
482 ext = None
485 ext = None
483
486
484 if ext is not None:
487 if ext is not None:
485 format = ext.lower()
488 format = ext.lower()
486 if ext == u'jpg' or ext == u'jpeg':
489 if ext == u'jpg' or ext == u'jpeg':
487 format = self._FMT_JPEG
490 format = self._FMT_JPEG
488 if ext == u'png':
491 if ext == u'png':
489 format = self._FMT_PNG
492 format = self._FMT_PNG
493 elif isinstance(data, bytes) and format == 'png':
494 # infer image type from image data header,
495 # only if format might not have been specified.
496 if data[:2] == _JPEG:
497 format = 'jpeg'
490
498
491 self.format = unicode(format).lower()
499 self.format = unicode(format).lower()
492 self.embed = embed if embed is not None else (url is None)
500 self.embed = embed if embed is not None else (url is None)
493
501
494 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
502 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
495 raise ValueError("Cannot embed the '%s' image format" % (self.format))
503 raise ValueError("Cannot embed the '%s' image format" % (self.format))
496 self.width = width
504 self.width = width
497 self.height = height
505 self.height = height
498 super(Image, self).__init__(data=data, url=url, filename=filename)
506 super(Image, self).__init__(data=data, url=url, filename=filename)
499
507
500 def reload(self):
508 def reload(self):
501 """Reload the raw data from file or URL."""
509 """Reload the raw data from file or URL."""
502 if self.embed:
510 if self.embed:
503 super(Image,self).reload()
511 super(Image,self).reload()
504
512
505 def _repr_html_(self):
513 def _repr_html_(self):
506 if not self.embed:
514 if not self.embed:
507 width = height = ''
515 width = height = ''
508 if self.width:
516 if self.width:
509 width = ' width="%d"' % self.width
517 width = ' width="%d"' % self.width
510 if self.height:
518 if self.height:
511 height = ' height="%d"' % self.height
519 height = ' height="%d"' % self.height
512 return u'<img src="%s"%s%s/>' % (self.url, width, height)
520 return u'<img src="%s"%s%s/>' % (self.url, width, height)
513
521
514 def _repr_png_(self):
522 def _repr_png_(self):
515 if self.embed and self.format == u'png':
523 if self.embed and self.format == u'png':
516 return self.data
524 return self.data
517
525
518 def _repr_jpeg_(self):
526 def _repr_jpeg_(self):
519 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
527 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
520 return self.data
528 return self.data
521
529
522 def _find_ext(self, s):
530 def _find_ext(self, s):
523 return unicode(s.split('.')[-1].lower())
531 return unicode(s.split('.')[-1].lower())
524
532
525
533
526 def clear_output(stdout=True, stderr=True, other=True):
534 def clear_output(stdout=True, stderr=True, other=True):
527 """Clear the output of the current cell receiving output.
535 """Clear the output of the current cell receiving output.
528
536
529 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
537 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
530 produced by display()) can be excluded from the clear event.
538 produced by display()) can be excluded from the clear event.
531
539
532 By default, everything is cleared.
540 By default, everything is cleared.
533
541
534 Parameters
542 Parameters
535 ----------
543 ----------
536 stdout : bool [default: True]
544 stdout : bool [default: True]
537 Whether to clear stdout.
545 Whether to clear stdout.
538 stderr : bool [default: True]
546 stderr : bool [default: True]
539 Whether to clear stderr.
547 Whether to clear stderr.
540 other : bool [default: True]
548 other : bool [default: True]
541 Whether to clear everything else that is not stdout/stderr
549 Whether to clear everything else that is not stdout/stderr
542 (e.g. figures,images,HTML, any result of display()).
550 (e.g. figures,images,HTML, any result of display()).
543 """
551 """
544 from IPython.core.interactiveshell import InteractiveShell
552 from IPython.core.interactiveshell import InteractiveShell
545 if InteractiveShell.initialized():
553 if InteractiveShell.initialized():
546 InteractiveShell.instance().display_pub.clear_output(
554 InteractiveShell.instance().display_pub.clear_output(
547 stdout=stdout, stderr=stderr, other=other,
555 stdout=stdout, stderr=stderr, other=other,
548 )
556 )
549 else:
557 else:
550 from IPython.utils import io
558 from IPython.utils import io
551 if stdout:
559 if stdout:
552 print('\033[2K\r', file=io.stdout, end='')
560 print('\033[2K\r', file=io.stdout, end='')
553 io.stdout.flush()
561 io.stdout.flush()
554 if stderr:
562 if stderr:
555 print('\033[2K\r', file=io.stderr, end='')
563 print('\033[2K\r', file=io.stderr, end='')
556 io.stderr.flush()
564 io.stderr.flush()
557
565
General Comments 0
You need to be logged in to leave comments. Login now