##// END OF EJS Templates
extract svg tag from svg files...
MinRK -
Show More
@@ -1,407 +1,434 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 xml.dom import minidom
21
20 from .displaypub import (
22 from .displaypub import (
21 publish_pretty, publish_html,
23 publish_pretty, publish_html,
22 publish_latex, publish_svg,
24 publish_latex, publish_svg,
23 publish_png, publish_json,
25 publish_png, publish_json,
24 publish_javascript, publish_jpeg
26 publish_javascript, publish_jpeg
25 )
27 )
26
28
27 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
28 # Main functions
30 # Main functions
29 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
30
32
31 def display(*objs, **kwargs):
33 def display(*objs, **kwargs):
32 """Display a Python object in all frontends.
34 """Display a Python object in all frontends.
33
35
34 By default all representations will be computed and sent to the frontends.
36 By default all representations will be computed and sent to the frontends.
35 Frontends can decide which representation is used and how.
37 Frontends can decide which representation is used and how.
36
38
37 Parameters
39 Parameters
38 ----------
40 ----------
39 objs : tuple of objects
41 objs : tuple of objects
40 The Python objects to display.
42 The Python objects to display.
41 include : list or tuple, optional
43 include : list or tuple, optional
42 A list of format type strings (MIME types) to include in the
44 A list of format type strings (MIME types) to include in the
43 format data dict. If this is set *only* the format types included
45 format data dict. If this is set *only* the format types included
44 in this list will be computed.
46 in this list will be computed.
45 exclude : list or tuple, optional
47 exclude : list or tuple, optional
46 A list of format type string (MIME types) to exclue in the format
48 A list of format type string (MIME types) to exclue in the format
47 data dict. If this is set all format types will be computed,
49 data dict. If this is set all format types will be computed,
48 except for those included in this argument.
50 except for those included in this argument.
49 """
51 """
50 include = kwargs.get('include')
52 include = kwargs.get('include')
51 exclude = kwargs.get('exclude')
53 exclude = kwargs.get('exclude')
52
54
53 from IPython.core.interactiveshell import InteractiveShell
55 from IPython.core.interactiveshell import InteractiveShell
54 inst = InteractiveShell.instance()
56 inst = InteractiveShell.instance()
55 format = inst.display_formatter.format
57 format = inst.display_formatter.format
56 publish = inst.display_pub.publish
58 publish = inst.display_pub.publish
57
59
58 for obj in objs:
60 for obj in objs:
59 format_dict = format(obj, include=include, exclude=exclude)
61 format_dict = format(obj, include=include, exclude=exclude)
60 publish('IPython.core.display.display', format_dict)
62 publish('IPython.core.display.display', format_dict)
61
63
62
64
63 def display_pretty(*objs, **kwargs):
65 def display_pretty(*objs, **kwargs):
64 """Display the pretty (default) representation of an object.
66 """Display the pretty (default) representation of an object.
65
67
66 Parameters
68 Parameters
67 ----------
69 ----------
68 objs : tuple of objects
70 objs : tuple of objects
69 The Python objects to display, or if raw=True raw text data to
71 The Python objects to display, or if raw=True raw text data to
70 display.
72 display.
71 raw : bool
73 raw : bool
72 Are the data objects raw data or Python objects that need to be
74 Are the data objects raw data or Python objects that need to be
73 formatted before display? [default: False]
75 formatted before display? [default: False]
74 """
76 """
75 raw = kwargs.pop('raw',False)
77 raw = kwargs.pop('raw',False)
76 if raw:
78 if raw:
77 for obj in objs:
79 for obj in objs:
78 publish_pretty(obj)
80 publish_pretty(obj)
79 else:
81 else:
80 display(*objs, include=['text/plain'])
82 display(*objs, include=['text/plain'])
81
83
82
84
83 def display_html(*objs, **kwargs):
85 def display_html(*objs, **kwargs):
84 """Display the HTML representation of an object.
86 """Display the HTML representation of an object.
85
87
86 Parameters
88 Parameters
87 ----------
89 ----------
88 objs : tuple of objects
90 objs : tuple of objects
89 The Python objects to display, or if raw=True raw HTML data to
91 The Python objects to display, or if raw=True raw HTML data to
90 display.
92 display.
91 raw : bool
93 raw : bool
92 Are the data objects raw data or Python objects that need to be
94 Are the data objects raw data or Python objects that need to be
93 formatted before display? [default: False]
95 formatted before display? [default: False]
94 """
96 """
95 raw = kwargs.pop('raw',False)
97 raw = kwargs.pop('raw',False)
96 if raw:
98 if raw:
97 for obj in objs:
99 for obj in objs:
98 publish_html(obj)
100 publish_html(obj)
99 else:
101 else:
100 display(*objs, include=['text/plain','text/html'])
102 display(*objs, include=['text/plain','text/html'])
101
103
102
104
103 def display_svg(*objs, **kwargs):
105 def display_svg(*objs, **kwargs):
104 """Display the SVG representation of an object.
106 """Display the SVG representation of an object.
105
107
106 Parameters
108 Parameters
107 ----------
109 ----------
108 objs : tuple of objects
110 objs : tuple of objects
109 The Python objects to display, or if raw=True raw svg data to
111 The Python objects to display, or if raw=True raw svg data to
110 display.
112 display.
111 raw : bool
113 raw : bool
112 Are the data objects raw data or Python objects that need to be
114 Are the data objects raw data or Python objects that need to be
113 formatted before display? [default: False]
115 formatted before display? [default: False]
114 """
116 """
115 raw = kwargs.pop('raw',False)
117 raw = kwargs.pop('raw',False)
116 if raw:
118 if raw:
117 for obj in objs:
119 for obj in objs:
118 publish_svg(obj)
120 publish_svg(obj)
119 else:
121 else:
120 display(*objs, include=['text/plain','image/svg+xml'])
122 display(*objs, include=['text/plain','image/svg+xml'])
121
123
122
124
123 def display_png(*objs, **kwargs):
125 def display_png(*objs, **kwargs):
124 """Display the PNG representation of an object.
126 """Display the PNG representation of an object.
125
127
126 Parameters
128 Parameters
127 ----------
129 ----------
128 objs : tuple of objects
130 objs : tuple of objects
129 The Python objects to display, or if raw=True raw png data to
131 The Python objects to display, or if raw=True raw png data to
130 display.
132 display.
131 raw : bool
133 raw : bool
132 Are the data objects raw data or Python objects that need to be
134 Are the data objects raw data or Python objects that need to be
133 formatted before display? [default: False]
135 formatted before display? [default: False]
134 """
136 """
135 raw = kwargs.pop('raw',False)
137 raw = kwargs.pop('raw',False)
136 if raw:
138 if raw:
137 for obj in objs:
139 for obj in objs:
138 publish_png(obj)
140 publish_png(obj)
139 else:
141 else:
140 display(*objs, include=['text/plain','image/png'])
142 display(*objs, include=['text/plain','image/png'])
141
143
142
144
143 def display_jpeg(*objs, **kwargs):
145 def display_jpeg(*objs, **kwargs):
144 """Display the JPEG representation of an object.
146 """Display the JPEG representation of an object.
145
147
146 Parameters
148 Parameters
147 ----------
149 ----------
148 objs : tuple of objects
150 objs : tuple of objects
149 The Python objects to display, or if raw=True raw JPEG data to
151 The Python objects to display, or if raw=True raw JPEG data to
150 display.
152 display.
151 raw : bool
153 raw : bool
152 Are the data objects raw data or Python objects that need to be
154 Are the data objects raw data or Python objects that need to be
153 formatted before display? [default: False]
155 formatted before display? [default: False]
154 """
156 """
155 raw = kwargs.pop('raw',False)
157 raw = kwargs.pop('raw',False)
156 if raw:
158 if raw:
157 for obj in objs:
159 for obj in objs:
158 publish_jpeg(obj)
160 publish_jpeg(obj)
159 else:
161 else:
160 display(*objs, include=['text/plain','image/jpeg'])
162 display(*objs, include=['text/plain','image/jpeg'])
161
163
162
164
163 def display_latex(*objs, **kwargs):
165 def display_latex(*objs, **kwargs):
164 """Display the LaTeX representation of an object.
166 """Display the LaTeX representation of an object.
165
167
166 Parameters
168 Parameters
167 ----------
169 ----------
168 objs : tuple of objects
170 objs : tuple of objects
169 The Python objects to display, or if raw=True raw latex data to
171 The Python objects to display, or if raw=True raw latex data to
170 display.
172 display.
171 raw : bool
173 raw : bool
172 Are the data objects raw data or Python objects that need to be
174 Are the data objects raw data or Python objects that need to be
173 formatted before display? [default: False]
175 formatted before display? [default: False]
174 """
176 """
175 raw = kwargs.pop('raw',False)
177 raw = kwargs.pop('raw',False)
176 if raw:
178 if raw:
177 for obj in objs:
179 for obj in objs:
178 publish_latex(obj)
180 publish_latex(obj)
179 else:
181 else:
180 display(*objs, include=['text/plain','text/latex'])
182 display(*objs, include=['text/plain','text/latex'])
181
183
182
184
183 def display_json(*objs, **kwargs):
185 def display_json(*objs, **kwargs):
184 """Display the JSON representation of an object.
186 """Display the JSON representation of an object.
185
187
186 Parameters
188 Parameters
187 ----------
189 ----------
188 objs : tuple of objects
190 objs : tuple of objects
189 The Python objects to display, or if raw=True raw json data to
191 The Python objects to display, or if raw=True raw json data to
190 display.
192 display.
191 raw : bool
193 raw : bool
192 Are the data objects raw data or Python objects that need to be
194 Are the data objects raw data or Python objects that need to be
193 formatted before display? [default: False]
195 formatted before display? [default: False]
194 """
196 """
195 raw = kwargs.pop('raw',False)
197 raw = kwargs.pop('raw',False)
196 if raw:
198 if raw:
197 for obj in objs:
199 for obj in objs:
198 publish_json(obj)
200 publish_json(obj)
199 else:
201 else:
200 display(*objs, include=['text/plain','application/json'])
202 display(*objs, include=['text/plain','application/json'])
201
203
202
204
203 def display_javascript(*objs, **kwargs):
205 def display_javascript(*objs, **kwargs):
204 """Display the Javascript representation of an object.
206 """Display the Javascript representation of an object.
205
207
206 Parameters
208 Parameters
207 ----------
209 ----------
208 objs : tuple of objects
210 objs : tuple of objects
209 The Python objects to display, or if raw=True raw javascript data to
211 The Python objects to display, or if raw=True raw javascript data to
210 display.
212 display.
211 raw : bool
213 raw : bool
212 Are the data objects raw data or Python objects that need to be
214 Are the data objects raw data or Python objects that need to be
213 formatted before display? [default: False]
215 formatted before display? [default: False]
214 """
216 """
215 raw = kwargs.pop('raw',False)
217 raw = kwargs.pop('raw',False)
216 if raw:
218 if raw:
217 for obj in objs:
219 for obj in objs:
218 publish_javascript(obj)
220 publish_javascript(obj)
219 else:
221 else:
220 display(*objs, include=['text/plain','application/javascript'])
222 display(*objs, include=['text/plain','application/javascript'])
221
223
222 #-----------------------------------------------------------------------------
224 #-----------------------------------------------------------------------------
223 # Smart classes
225 # Smart classes
224 #-----------------------------------------------------------------------------
226 #-----------------------------------------------------------------------------
225
227
226
228
227 class DisplayObject(object):
229 class DisplayObject(object):
228 """An object that wraps data to be displayed."""
230 """An object that wraps data to be displayed."""
229
231
230 _read_flags = 'r'
232 _read_flags = 'r'
231
233
232 def __init__(self, data=None, url=None, filename=None):
234 def __init__(self, data=None, url=None, filename=None):
233 """Create a display object given raw data.
235 """Create a display object given raw data.
234
236
235 When this object is returned by an expression or passed to the
237 When this object is returned by an expression or passed to the
236 display function, it will result in the data being displayed
238 display function, it will result in the data being displayed
237 in the frontend. The MIME type of the data should match the
239 in the frontend. The MIME type of the data should match the
238 subclasses used, so the Png subclass should be used for 'image/png'
240 subclasses used, so the Png subclass should be used for 'image/png'
239 data. If the data is a URL, the data will first be downloaded
241 data. If the data is a URL, the data will first be downloaded
240 and then displayed. If
242 and then displayed. If
241
243
242 Parameters
244 Parameters
243 ----------
245 ----------
244 data : unicode, str or bytes
246 data : unicode, str or bytes
245 The raw data or a URL to download the data from.
247 The raw data or a URL to download the data from.
246 url : unicode
248 url : unicode
247 A URL to download the data from.
249 A URL to download the data from.
248 filename : unicode
250 filename : unicode
249 Path to a local file to load the data from.
251 Path to a local file to load the data from.
250 """
252 """
251 if data is not None and data.startswith('http'):
253 if data is not None and data.startswith('http'):
252 self.url = data
254 self.url = data
253 self.filename = None
255 self.filename = None
254 self.data = None
256 self.data = None
255 else:
257 else:
256 self.data = data
258 self.data = data
257 self.url = url
259 self.url = url
258 self.filename = None if filename is None else unicode(filename)
260 self.filename = None if filename is None else unicode(filename)
259 self.reload()
261 self.reload()
260
262
261 def reload(self):
263 def reload(self):
262 """Reload the raw data from file or URL."""
264 """Reload the raw data from file or URL."""
263 if self.filename is not None:
265 if self.filename is not None:
264 with open(self.filename, self._read_flags) as f:
266 with open(self.filename, self._read_flags) as f:
265 self.data = f.read()
267 self.data = f.read()
266 elif self.url is not None:
268 elif self.url is not None:
267 try:
269 try:
268 import urllib2
270 import urllib2
269 response = urllib2.urlopen(self.url)
271 response = urllib2.urlopen(self.url)
270 self.data = response.read()
272 self.data = response.read()
271 # extract encoding from header, if there is one:
273 # extract encoding from header, if there is one:
272 encoding = None
274 encoding = None
273 for sub in response.headers['content-type'].split(';'):
275 for sub in response.headers['content-type'].split(';'):
274 sub = sub.strip()
276 sub = sub.strip()
275 if sub.startswith('charset'):
277 if sub.startswith('charset'):
276 encoding = sub.split('=')[-1].strip()
278 encoding = sub.split('=')[-1].strip()
277 break
279 break
278 # decode data, if an encoding was specified
280 # decode data, if an encoding was specified
279 if encoding:
281 if encoding:
280 self.data = self.data.decode(encoding, 'replace')
282 self.data = self.data.decode(encoding, 'replace')
281 except:
283 except:
282 self.data = None
284 self.data = None
283
285
284 class Pretty(DisplayObject):
286 class Pretty(DisplayObject):
285
287
286 def _repr_pretty_(self):
288 def _repr_pretty_(self):
287 return self.data
289 return self.data
288
290
289
291
290 class HTML(DisplayObject):
292 class HTML(DisplayObject):
291
293
292 def _repr_html_(self):
294 def _repr_html_(self):
293 return self.data
295 return self.data
294
296
295
297
296 class Math(DisplayObject):
298 class Math(DisplayObject):
297
299
298 def _repr_latex_(self):
300 def _repr_latex_(self):
299 return self.data
301 return self.data
300
302
301
303
302 class SVG(DisplayObject):
304 class SVG(DisplayObject):
303
305
306 # wrap data in a property, which extracts the <svg> tag, discarding
307 # document headers
308 _data = None
309
310 @property
311 def data(self):
312 return self._data
313
314 @data.setter
315 def data(self, svg):
316 if svg is None:
317 self._data = None
318 return
319 # parse into dom object
320 x = minidom.parseString(svg)
321 # get svg tag (should be 1)
322 found_svg = x.getElementsByTagName('svg')
323 if found_svg:
324 svg = found_svg[0].toxml()
325 else:
326 # fallback on the input, trust the user
327 # but this is probably an error.
328 pass
329 self._data = svg
330
304 def _repr_svg_(self):
331 def _repr_svg_(self):
305 return self.data
332 return self.data
306
333
307
334
308 class JSON(DisplayObject):
335 class JSON(DisplayObject):
309
336
310 def _repr_json_(self):
337 def _repr_json_(self):
311 return self.data
338 return self.data
312
339
313
340
314 class Javascript(DisplayObject):
341 class Javascript(DisplayObject):
315
342
316 def _repr_javascript_(self):
343 def _repr_javascript_(self):
317 return self.data
344 return self.data
318
345
319
346
320 class Image(DisplayObject):
347 class Image(DisplayObject):
321
348
322 _read_flags = 'rb'
349 _read_flags = 'rb'
323
350
324 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=False):
351 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=False):
325 """Create a display an PNG/JPEG image given raw data.
352 """Create a display an PNG/JPEG image given raw data.
326
353
327 When this object is returned by an expression or passed to the
354 When this object is returned by an expression or passed to the
328 display function, it will result in the image being displayed
355 display function, it will result in the image being displayed
329 in the frontend.
356 in the frontend.
330
357
331 Parameters
358 Parameters
332 ----------
359 ----------
333 data : unicode, str or bytes
360 data : unicode, str or bytes
334 The raw data or a URL to download the data from.
361 The raw data or a URL to download the data from.
335 url : unicode
362 url : unicode
336 A URL to download the data from.
363 A URL to download the data from.
337 filename : unicode
364 filename : unicode
338 Path to a local file to load the data from.
365 Path to a local file to load the data from.
339 format : unicode
366 format : unicode
340 The format of the image data (png/jpeg/jpg). If a filename or URL is given
367 The format of the image data (png/jpeg/jpg). If a filename or URL is given
341 for format will be inferred from the filename extension.
368 for format will be inferred from the filename extension.
342 embed : bool
369 embed : bool
343 Should the image data be embedded in the notebook using a data URI (True)
370 Should the image data be embedded in the notebook using a data URI (True)
344 or be loaded using an <img> tag. Set this to True if you want the image
371 or be loaded using an <img> tag. Set this to True if you want the image
345 to be viewable later with no internet connection. If a filename is given
372 to be viewable later with no internet connection. If a filename is given
346 embed is always set to True.
373 embed is always set to True.
347 """
374 """
348 if filename is not None:
375 if filename is not None:
349 ext = self._find_ext(filename)
376 ext = self._find_ext(filename)
350 elif url is not None:
377 elif url is not None:
351 ext = self._find_ext(url)
378 ext = self._find_ext(url)
352 elif data.startswith('http'):
379 elif data.startswith('http'):
353 ext = self._find_ext(data)
380 ext = self._find_ext(data)
354 else:
381 else:
355 ext = None
382 ext = None
356 if ext is not None:
383 if ext is not None:
357 if ext == u'jpg' or ext == u'jpeg':
384 if ext == u'jpg' or ext == u'jpeg':
358 format = u'jpeg'
385 format = u'jpeg'
359 if ext == u'png':
386 if ext == u'png':
360 format = u'png'
387 format = u'png'
361 self.format = unicode(format).lower()
388 self.format = unicode(format).lower()
362 self.embed = True if filename is not None else embed
389 self.embed = True if filename is not None else embed
363 super(Image, self).__init__(data=data, url=url, filename=filename)
390 super(Image, self).__init__(data=data, url=url, filename=filename)
364
391
365 def reload(self):
392 def reload(self):
366 """Reload the raw data from file or URL."""
393 """Reload the raw data from file or URL."""
367 if self.embed:
394 if self.embed:
368 super(Image,self).reload()
395 super(Image,self).reload()
369
396
370 def _repr_html_(self):
397 def _repr_html_(self):
371 if not self.embed:
398 if not self.embed:
372 return u'<img src="%s" />' % self.url
399 return u'<img src="%s" />' % self.url
373
400
374 def _repr_png_(self):
401 def _repr_png_(self):
375 if self.embed and self.format == u'png':
402 if self.embed and self.format == u'png':
376 return self.data
403 return self.data
377
404
378 def _repr_jpeg_(self):
405 def _repr_jpeg_(self):
379 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
406 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
380 return self.data
407 return self.data
381
408
382 def _find_ext(self, s):
409 def _find_ext(self, s):
383 return unicode(s.split('.')[-1].lower())
410 return unicode(s.split('.')[-1].lower())
384
411
385
412
386 def clear_output(stdout=True, stderr=True, other=True):
413 def clear_output(stdout=True, stderr=True, other=True):
387 """Clear the output of the current cell receiving output.
414 """Clear the output of the current cell receiving output.
388
415
389 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
416 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
390 produced by display()) can be excluded from the clear event.
417 produced by display()) can be excluded from the clear event.
391
418
392 By default, everything is cleared.
419 By default, everything is cleared.
393
420
394 Parameters
421 Parameters
395 ----------
422 ----------
396 stdout : bool [default: True]
423 stdout : bool [default: True]
397 Whether to clear stdout.
424 Whether to clear stdout.
398 stderr : bool [default: True]
425 stderr : bool [default: True]
399 Whether to clear stderr.
426 Whether to clear stderr.
400 other : bool [default: True]
427 other : bool [default: True]
401 Whether to clear everything else that is not stdout/stderr
428 Whether to clear everything else that is not stdout/stderr
402 (e.g. figures,images,HTML, any result of display()).
429 (e.g. figures,images,HTML, any result of display()).
403 """
430 """
404 from IPython.core.interactiveshell import InteractiveShell
431 from IPython.core.interactiveshell import InteractiveShell
405 InteractiveShell.instance().display_pub.clear_output(
432 InteractiveShell.instance().display_pub.clear_output(
406 stdout=stdout, stderr=stderr, other=other,
433 stdout=stdout, stderr=stderr, other=other,
407 )
434 )
General Comments 0
You need to be logged in to leave comments. Login now