Show More
@@ -1,771 +1,772 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) 2013 The IPython Development Team |
|
10 | # Copyright (C) 2013 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 | import os |
|
22 | import os | |
23 | import struct |
|
23 | import struct | |
24 |
|
24 | |||
25 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, |
|
25 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, | |
26 | unicode_type) |
|
26 | unicode_type) | |
27 | from IPython.testing.skipdoctest import skip_doctest |
|
27 | from IPython.testing.skipdoctest import skip_doctest | |
28 | from .displaypub import publish_display_data |
|
28 | from .displaypub import publish_display_data | |
29 |
|
29 | |||
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 | # utility functions |
|
31 | # utility functions | |
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 |
|
33 | |||
34 | def _safe_exists(path): |
|
34 | def _safe_exists(path): | |
35 | """Check path, but don't let exceptions raise""" |
|
35 | """Check path, but don't let exceptions raise""" | |
36 | try: |
|
36 | try: | |
37 | return os.path.exists(path) |
|
37 | return os.path.exists(path) | |
38 | except Exception: |
|
38 | except Exception: | |
39 | return False |
|
39 | return False | |
40 |
|
40 | |||
41 | def _merge(d1, d2): |
|
41 | def _merge(d1, d2): | |
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. | |
43 |
|
43 | |||
44 | Updates d1 in-place |
|
44 | Updates d1 in-place | |
45 | """ |
|
45 | """ | |
46 |
|
46 | |||
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |
48 | return d2 |
|
48 | return d2 | |
49 | for key, value in d2.items(): |
|
49 | for key, value in d2.items(): | |
50 | d1[key] = _merge(d1.get(key), value) |
|
50 | d1[key] = _merge(d1.get(key), value) | |
51 | return d1 |
|
51 | return d1 | |
52 |
|
52 | |||
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
54 | """internal implementation of all display_foo methods |
|
54 | """internal implementation of all display_foo methods | |
55 |
|
55 | |||
56 | Parameters |
|
56 | Parameters | |
57 | ---------- |
|
57 | ---------- | |
58 | mimetype : str |
|
58 | mimetype : str | |
59 | The mimetype to be published (e.g. 'image/png') |
|
59 | The mimetype to be published (e.g. 'image/png') | |
60 | objs : tuple of objects |
|
60 | objs : tuple of objects | |
61 | The Python objects to display, or if raw=True raw text data to |
|
61 | The Python objects to display, or if raw=True raw text data to | |
62 | display. |
|
62 | display. | |
63 | raw : bool |
|
63 | raw : bool | |
64 | Are the data objects raw data or Python objects that need to be |
|
64 | Are the data objects raw data or Python objects that need to be | |
65 | formatted before display? [default: False] |
|
65 | formatted before display? [default: False] | |
66 | metadata : dict (optional) |
|
66 | metadata : dict (optional) | |
67 | Metadata to be associated with the specific mimetype output. |
|
67 | Metadata to be associated with the specific mimetype output. | |
68 | """ |
|
68 | """ | |
69 | if metadata: |
|
69 | if metadata: | |
70 | metadata = {mimetype: metadata} |
|
70 | metadata = {mimetype: metadata} | |
71 | if raw: |
|
71 | if raw: | |
72 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
72 | # turn list of pngdata into list of { 'image/png': pngdata } | |
73 | objs = [ {mimetype: obj} for obj in objs ] |
|
73 | objs = [ {mimetype: obj} for obj in objs ] | |
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | |
75 |
|
75 | |||
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | # Main functions |
|
77 | # Main functions | |
78 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | def display(*objs, **kwargs): |
|
80 | def display(*objs, **kwargs): | |
81 | """Display a Python object in all frontends. |
|
81 | """Display a Python object in all frontends. | |
82 |
|
82 | |||
83 | By default all representations will be computed and sent to the frontends. |
|
83 | By default all representations will be computed and sent to the frontends. | |
84 | Frontends can decide which representation is used and how. |
|
84 | Frontends can decide which representation is used and how. | |
85 |
|
85 | |||
86 | Parameters |
|
86 | Parameters | |
87 | ---------- |
|
87 | ---------- | |
88 | objs : tuple of objects |
|
88 | objs : tuple of objects | |
89 | The Python objects to display. |
|
89 | The Python objects to display. | |
90 | raw : bool, optional |
|
90 | raw : bool, optional | |
91 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
91 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |
92 | or Python objects that need to be formatted before display? [default: False] |
|
92 | or Python objects that need to be formatted before display? [default: False] | |
93 | include : list or tuple, optional |
|
93 | include : list or tuple, optional | |
94 | A list of format type strings (MIME types) to include in the |
|
94 | A list of format type strings (MIME types) to include in the | |
95 | format data dict. If this is set *only* the format types included |
|
95 | format data dict. If this is set *only* the format types included | |
96 | in this list will be computed. |
|
96 | in this list will be computed. | |
97 | exclude : list or tuple, optional |
|
97 | exclude : list or tuple, optional | |
98 | A list of format type strings (MIME types) to exclude in the format |
|
98 | A list of format type strings (MIME types) to exclude in the format | |
99 | data dict. If this is set all format types will be computed, |
|
99 | data dict. If this is set all format types will be computed, | |
100 | except for those included in this argument. |
|
100 | except for those included in this argument. | |
101 | metadata : dict, optional |
|
101 | metadata : dict, optional | |
102 | A dictionary of metadata to associate with the output. |
|
102 | A dictionary of metadata to associate with the output. | |
103 | mime-type keys in this dictionary will be associated with the individual |
|
103 | mime-type keys in this dictionary will be associated with the individual | |
104 | representation formats, if they exist. |
|
104 | representation formats, if they exist. | |
105 | """ |
|
105 | """ | |
106 | raw = kwargs.get('raw', False) |
|
106 | raw = kwargs.get('raw', False) | |
107 | include = kwargs.get('include') |
|
107 | include = kwargs.get('include') | |
108 | exclude = kwargs.get('exclude') |
|
108 | exclude = kwargs.get('exclude') | |
109 | metadata = kwargs.get('metadata') |
|
109 | metadata = kwargs.get('metadata') | |
110 |
|
110 | |||
111 | from IPython.core.interactiveshell import InteractiveShell |
|
111 | from IPython.core.interactiveshell import InteractiveShell | |
112 |
|
112 | |||
113 | if not raw: |
|
113 | if not raw: | |
114 | format = InteractiveShell.instance().display_formatter.format |
|
114 | format = InteractiveShell.instance().display_formatter.format | |
115 |
|
115 | |||
116 | for obj in objs: |
|
116 | for obj in objs: | |
117 |
|
117 | |||
118 | # If _ipython_display_ is defined, use that to display this object. |
|
118 | # If _ipython_display_ is defined, use that to display this object. | |
119 | display_method = getattr(obj, '_ipython_display_', None) |
|
119 | display_method = getattr(obj, '_ipython_display_', None) | |
120 | if display_method is not None: |
|
120 | if display_method is not None: | |
121 | try: |
|
121 | try: | |
122 | display_method(**kwargs) |
|
122 | display_method(**kwargs) | |
123 | except NotImplementedError: |
|
123 | except NotImplementedError: | |
124 | pass |
|
124 | pass | |
125 | else: |
|
125 | else: | |
126 | continue |
|
126 | continue | |
127 | if raw: |
|
127 | if raw: | |
128 | publish_display_data('display', obj, metadata) |
|
128 | publish_display_data('display', obj, metadata) | |
129 | else: |
|
129 | else: | |
130 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
130 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |
131 | if metadata: |
|
131 | if metadata: | |
132 | # kwarg-specified metadata gets precedence |
|
132 | # kwarg-specified metadata gets precedence | |
133 | _merge(md_dict, metadata) |
|
133 | _merge(md_dict, metadata) | |
134 | publish_display_data('display', format_dict, md_dict) |
|
134 | publish_display_data('display', format_dict, md_dict) | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | def display_pretty(*objs, **kwargs): |
|
137 | def display_pretty(*objs, **kwargs): | |
138 | """Display the pretty (default) representation of an object. |
|
138 | """Display the pretty (default) representation of an object. | |
139 |
|
139 | |||
140 | Parameters |
|
140 | Parameters | |
141 | ---------- |
|
141 | ---------- | |
142 | objs : tuple of objects |
|
142 | objs : tuple of objects | |
143 | The Python objects to display, or if raw=True raw text data to |
|
143 | The Python objects to display, or if raw=True raw text data to | |
144 | display. |
|
144 | display. | |
145 | raw : bool |
|
145 | raw : bool | |
146 | Are the data objects raw data or Python objects that need to be |
|
146 | Are the data objects raw data or Python objects that need to be | |
147 | formatted before display? [default: False] |
|
147 | formatted before display? [default: False] | |
148 | metadata : dict (optional) |
|
148 | metadata : dict (optional) | |
149 | Metadata to be associated with the specific mimetype output. |
|
149 | Metadata to be associated with the specific mimetype output. | |
150 | """ |
|
150 | """ | |
151 | _display_mimetype('text/plain', objs, **kwargs) |
|
151 | _display_mimetype('text/plain', objs, **kwargs) | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def display_html(*objs, **kwargs): |
|
154 | def display_html(*objs, **kwargs): | |
155 | """Display the HTML representation of an object. |
|
155 | """Display the HTML representation of an object. | |
156 |
|
156 | |||
157 | Parameters |
|
157 | Parameters | |
158 | ---------- |
|
158 | ---------- | |
159 | objs : tuple of objects |
|
159 | objs : tuple of objects | |
160 | The Python objects to display, or if raw=True raw HTML data to |
|
160 | The Python objects to display, or if raw=True raw HTML data to | |
161 | display. |
|
161 | display. | |
162 | raw : bool |
|
162 | raw : bool | |
163 | Are the data objects raw data or Python objects that need to be |
|
163 | Are the data objects raw data or Python objects that need to be | |
164 | formatted before display? [default: False] |
|
164 | formatted before display? [default: False] | |
165 | metadata : dict (optional) |
|
165 | metadata : dict (optional) | |
166 | Metadata to be associated with the specific mimetype output. |
|
166 | Metadata to be associated with the specific mimetype output. | |
167 | """ |
|
167 | """ | |
168 | _display_mimetype('text/html', objs, **kwargs) |
|
168 | _display_mimetype('text/html', objs, **kwargs) | |
169 |
|
169 | |||
170 |
|
170 | |||
171 | def display_svg(*objs, **kwargs): |
|
171 | def display_svg(*objs, **kwargs): | |
172 | """Display the SVG representation of an object. |
|
172 | """Display the SVG representation of an object. | |
173 |
|
173 | |||
174 | Parameters |
|
174 | Parameters | |
175 | ---------- |
|
175 | ---------- | |
176 | objs : tuple of objects |
|
176 | objs : tuple of objects | |
177 | The Python objects to display, or if raw=True raw svg data to |
|
177 | The Python objects to display, or if raw=True raw svg data to | |
178 | display. |
|
178 | display. | |
179 | raw : bool |
|
179 | raw : bool | |
180 | Are the data objects raw data or Python objects that need to be |
|
180 | Are the data objects raw data or Python objects that need to be | |
181 | formatted before display? [default: False] |
|
181 | formatted before display? [default: False] | |
182 | metadata : dict (optional) |
|
182 | metadata : dict (optional) | |
183 | Metadata to be associated with the specific mimetype output. |
|
183 | Metadata to be associated with the specific mimetype output. | |
184 | """ |
|
184 | """ | |
185 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
185 | _display_mimetype('image/svg+xml', objs, **kwargs) | |
186 |
|
186 | |||
187 |
|
187 | |||
188 | def display_png(*objs, **kwargs): |
|
188 | def display_png(*objs, **kwargs): | |
189 | """Display the PNG representation of an object. |
|
189 | """Display the PNG representation of an object. | |
190 |
|
190 | |||
191 | Parameters |
|
191 | Parameters | |
192 | ---------- |
|
192 | ---------- | |
193 | objs : tuple of objects |
|
193 | objs : tuple of objects | |
194 | The Python objects to display, or if raw=True raw png data to |
|
194 | The Python objects to display, or if raw=True raw png data to | |
195 | display. |
|
195 | display. | |
196 | raw : bool |
|
196 | raw : bool | |
197 | Are the data objects raw data or Python objects that need to be |
|
197 | Are the data objects raw data or Python objects that need to be | |
198 | formatted before display? [default: False] |
|
198 | formatted before display? [default: False] | |
199 | metadata : dict (optional) |
|
199 | metadata : dict (optional) | |
200 | Metadata to be associated with the specific mimetype output. |
|
200 | Metadata to be associated with the specific mimetype output. | |
201 | """ |
|
201 | """ | |
202 | _display_mimetype('image/png', objs, **kwargs) |
|
202 | _display_mimetype('image/png', objs, **kwargs) | |
203 |
|
203 | |||
204 |
|
204 | |||
205 | def display_jpeg(*objs, **kwargs): |
|
205 | def display_jpeg(*objs, **kwargs): | |
206 | """Display the JPEG representation of an object. |
|
206 | """Display the JPEG representation of an object. | |
207 |
|
207 | |||
208 | Parameters |
|
208 | Parameters | |
209 | ---------- |
|
209 | ---------- | |
210 | objs : tuple of objects |
|
210 | objs : tuple of objects | |
211 | The Python objects to display, or if raw=True raw JPEG data to |
|
211 | The Python objects to display, or if raw=True raw JPEG data to | |
212 | display. |
|
212 | display. | |
213 | raw : bool |
|
213 | raw : bool | |
214 | 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 | |
215 | formatted before display? [default: False] |
|
215 | formatted before display? [default: False] | |
216 | metadata : dict (optional) |
|
216 | metadata : dict (optional) | |
217 | Metadata to be associated with the specific mimetype output. |
|
217 | Metadata to be associated with the specific mimetype output. | |
218 | """ |
|
218 | """ | |
219 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
219 | _display_mimetype('image/jpeg', objs, **kwargs) | |
220 |
|
220 | |||
221 |
|
221 | |||
222 | def display_latex(*objs, **kwargs): |
|
222 | def display_latex(*objs, **kwargs): | |
223 | """Display the LaTeX representation of an object. |
|
223 | """Display the LaTeX representation of an object. | |
224 |
|
224 | |||
225 | Parameters |
|
225 | Parameters | |
226 | ---------- |
|
226 | ---------- | |
227 | objs : tuple of objects |
|
227 | objs : tuple of objects | |
228 | The Python objects to display, or if raw=True raw latex data to |
|
228 | The Python objects to display, or if raw=True raw latex data to | |
229 | display. |
|
229 | display. | |
230 | raw : bool |
|
230 | raw : bool | |
231 | Are the data objects raw data or Python objects that need to be |
|
231 | Are the data objects raw data or Python objects that need to be | |
232 | formatted before display? [default: False] |
|
232 | formatted before display? [default: False] | |
233 | metadata : dict (optional) |
|
233 | metadata : dict (optional) | |
234 | Metadata to be associated with the specific mimetype output. |
|
234 | Metadata to be associated with the specific mimetype output. | |
235 | """ |
|
235 | """ | |
236 | _display_mimetype('text/latex', objs, **kwargs) |
|
236 | _display_mimetype('text/latex', objs, **kwargs) | |
237 |
|
237 | |||
238 |
|
238 | |||
239 | def display_json(*objs, **kwargs): |
|
239 | def display_json(*objs, **kwargs): | |
240 | """Display the JSON representation of an object. |
|
240 | """Display the JSON representation of an object. | |
241 |
|
241 | |||
242 | Note that not many frontends support displaying JSON. |
|
242 | Note that not many frontends support displaying JSON. | |
243 |
|
243 | |||
244 | Parameters |
|
244 | Parameters | |
245 | ---------- |
|
245 | ---------- | |
246 | objs : tuple of objects |
|
246 | objs : tuple of objects | |
247 | The Python objects to display, or if raw=True raw json data to |
|
247 | The Python objects to display, or if raw=True raw json data to | |
248 | display. |
|
248 | display. | |
249 | raw : bool |
|
249 | raw : bool | |
250 | Are the data objects raw data or Python objects that need to be |
|
250 | Are the data objects raw data or Python objects that need to be | |
251 | formatted before display? [default: False] |
|
251 | formatted before display? [default: False] | |
252 | metadata : dict (optional) |
|
252 | metadata : dict (optional) | |
253 | Metadata to be associated with the specific mimetype output. |
|
253 | Metadata to be associated with the specific mimetype output. | |
254 | """ |
|
254 | """ | |
255 | _display_mimetype('application/json', objs, **kwargs) |
|
255 | _display_mimetype('application/json', objs, **kwargs) | |
256 |
|
256 | |||
257 |
|
257 | |||
258 | def display_javascript(*objs, **kwargs): |
|
258 | def display_javascript(*objs, **kwargs): | |
259 | """Display the Javascript representation of an object. |
|
259 | """Display the Javascript representation of an object. | |
260 |
|
260 | |||
261 | Parameters |
|
261 | Parameters | |
262 | ---------- |
|
262 | ---------- | |
263 | objs : tuple of objects |
|
263 | objs : tuple of objects | |
264 | The Python objects to display, or if raw=True raw javascript data to |
|
264 | The Python objects to display, or if raw=True raw javascript data to | |
265 | display. |
|
265 | display. | |
266 | raw : bool |
|
266 | raw : bool | |
267 | Are the data objects raw data or Python objects that need to be |
|
267 | Are the data objects raw data or Python objects that need to be | |
268 | formatted before display? [default: False] |
|
268 | formatted before display? [default: False] | |
269 | metadata : dict (optional) |
|
269 | metadata : dict (optional) | |
270 | Metadata to be associated with the specific mimetype output. |
|
270 | Metadata to be associated with the specific mimetype output. | |
271 | """ |
|
271 | """ | |
272 | _display_mimetype('application/javascript', objs, **kwargs) |
|
272 | _display_mimetype('application/javascript', objs, **kwargs) | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | def display_pdf(*objs, **kwargs): |
|
275 | def display_pdf(*objs, **kwargs): | |
276 | """Display the PDF representation of an object. |
|
276 | """Display the PDF representation of an object. | |
277 |
|
277 | |||
278 | Parameters |
|
278 | Parameters | |
279 | ---------- |
|
279 | ---------- | |
280 | objs : tuple of objects |
|
280 | objs : tuple of objects | |
281 | The Python objects to display, or if raw=True raw javascript data to |
|
281 | The Python objects to display, or if raw=True raw javascript data to | |
282 | display. |
|
282 | display. | |
283 | raw : bool |
|
283 | raw : bool | |
284 | Are the data objects raw data or Python objects that need to be |
|
284 | Are the data objects raw data or Python objects that need to be | |
285 | formatted before display? [default: False] |
|
285 | formatted before display? [default: False] | |
286 | metadata : dict (optional) |
|
286 | metadata : dict (optional) | |
287 | Metadata to be associated with the specific mimetype output. |
|
287 | Metadata to be associated with the specific mimetype output. | |
288 | """ |
|
288 | """ | |
289 | _display_mimetype('application/pdf', objs, **kwargs) |
|
289 | _display_mimetype('application/pdf', objs, **kwargs) | |
290 |
|
290 | |||
291 |
|
291 | |||
292 | #----------------------------------------------------------------------------- |
|
292 | #----------------------------------------------------------------------------- | |
293 | # Smart classes |
|
293 | # Smart classes | |
294 | #----------------------------------------------------------------------------- |
|
294 | #----------------------------------------------------------------------------- | |
295 |
|
295 | |||
296 |
|
296 | |||
297 | class DisplayObject(object): |
|
297 | class DisplayObject(object): | |
298 | """An object that wraps data to be displayed.""" |
|
298 | """An object that wraps data to be displayed.""" | |
299 |
|
299 | |||
300 | _read_flags = 'r' |
|
300 | _read_flags = 'r' | |
301 |
|
301 | |||
302 | def __init__(self, data=None, url=None, filename=None): |
|
302 | def __init__(self, data=None, url=None, filename=None): | |
303 | """Create a display object given raw data. |
|
303 | """Create a display object given raw data. | |
304 |
|
304 | |||
305 | When this object is returned by an expression or passed to the |
|
305 | When this object is returned by an expression or passed to the | |
306 | display function, it will result in the data being displayed |
|
306 | display function, it will result in the data being displayed | |
307 | in the frontend. The MIME type of the data should match the |
|
307 | in the frontend. The MIME type of the data should match the | |
308 | subclasses used, so the Png subclass should be used for 'image/png' |
|
308 | subclasses used, so the Png subclass should be used for 'image/png' | |
309 | data. If the data is a URL, the data will first be downloaded |
|
309 | data. If the data is a URL, the data will first be downloaded | |
310 | and then displayed. If |
|
310 | and then displayed. If | |
311 |
|
311 | |||
312 | Parameters |
|
312 | Parameters | |
313 | ---------- |
|
313 | ---------- | |
314 | data : unicode, str or bytes |
|
314 | data : unicode, str or bytes | |
315 | The raw data or a URL or file to load the data from |
|
315 | The raw data or a URL or file to load the data from | |
316 | url : unicode |
|
316 | url : unicode | |
317 | A URL to download the data from. |
|
317 | A URL to download the data from. | |
318 | filename : unicode |
|
318 | filename : unicode | |
319 | Path to a local file to load the data from. |
|
319 | Path to a local file to load the data from. | |
320 | """ |
|
320 | """ | |
321 | if data is not None and isinstance(data, string_types): |
|
321 | if data is not None and isinstance(data, string_types): | |
322 | if data.startswith('http') and url is None: |
|
322 | if data.startswith('http') and url is None: | |
323 | url = data |
|
323 | url = data | |
324 | filename = None |
|
324 | filename = None | |
325 | data = None |
|
325 | data = None | |
326 | elif _safe_exists(data) and filename is None: |
|
326 | elif _safe_exists(data) and filename is None: | |
327 | url = None |
|
327 | url = None | |
328 | filename = data |
|
328 | filename = data | |
329 | data = None |
|
329 | data = None | |
330 |
|
330 | |||
331 | self.data = data |
|
331 | self.data = data | |
332 | self.url = url |
|
332 | self.url = url | |
333 | self.filename = None if filename is None else unicode_type(filename) |
|
333 | self.filename = None if filename is None else unicode_type(filename) | |
334 |
|
334 | |||
335 | self.reload() |
|
335 | self.reload() | |
336 | self._check_data() |
|
336 | self._check_data() | |
337 |
|
337 | |||
338 | def _check_data(self): |
|
338 | def _check_data(self): | |
339 | """Override in subclasses if there's something to check.""" |
|
339 | """Override in subclasses if there's something to check.""" | |
340 | pass |
|
340 | pass | |
341 |
|
341 | |||
342 | def reload(self): |
|
342 | def reload(self): | |
343 | """Reload the raw data from file or URL.""" |
|
343 | """Reload the raw data from file or URL.""" | |
344 | if self.filename is not None: |
|
344 | if self.filename is not None: | |
345 | with open(self.filename, self._read_flags) as f: |
|
345 | with open(self.filename, self._read_flags) as f: | |
346 | self.data = f.read() |
|
346 | self.data = f.read() | |
347 | elif self.url is not None: |
|
347 | elif self.url is not None: | |
348 | try: |
|
348 | try: | |
349 | try: |
|
349 | try: | |
350 | from urllib.request import urlopen # Py3 |
|
350 | from urllib.request import urlopen # Py3 | |
351 | except ImportError: |
|
351 | except ImportError: | |
352 | from urllib2 import urlopen |
|
352 | from urllib2 import urlopen | |
353 | response = urlopen(self.url) |
|
353 | response = urlopen(self.url) | |
354 | self.data = response.read() |
|
354 | self.data = response.read() | |
355 | # extract encoding from header, if there is one: |
|
355 | # extract encoding from header, if there is one: | |
356 | encoding = None |
|
356 | encoding = None | |
357 | for sub in response.headers['content-type'].split(';'): |
|
357 | for sub in response.headers['content-type'].split(';'): | |
358 | sub = sub.strip() |
|
358 | sub = sub.strip() | |
359 | if sub.startswith('charset'): |
|
359 | if sub.startswith('charset'): | |
360 | encoding = sub.split('=')[-1].strip() |
|
360 | encoding = sub.split('=')[-1].strip() | |
361 | break |
|
361 | break | |
362 | # decode data, if an encoding was specified |
|
362 | # decode data, if an encoding was specified | |
363 | if encoding: |
|
363 | if encoding: | |
364 | self.data = self.data.decode(encoding, 'replace') |
|
364 | self.data = self.data.decode(encoding, 'replace') | |
365 | except: |
|
365 | except: | |
366 | self.data = None |
|
366 | self.data = None | |
367 |
|
367 | |||
368 | class TextDisplayObject(DisplayObject): |
|
368 | class TextDisplayObject(DisplayObject): | |
369 | """Validate that display data is text""" |
|
369 | """Validate that display data is text""" | |
370 | def _check_data(self): |
|
370 | def _check_data(self): | |
371 | if self.data is not None and not isinstance(self.data, string_types): |
|
371 | if self.data is not None and not isinstance(self.data, string_types): | |
372 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
372 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | |
373 |
|
373 | |||
374 | class Pretty(TextDisplayObject): |
|
374 | class Pretty(TextDisplayObject): | |
375 |
|
375 | |||
376 | def _repr_pretty_(self): |
|
376 | def _repr_pretty_(self): | |
377 | return self.data |
|
377 | return self.data | |
378 |
|
378 | |||
379 |
|
379 | |||
380 | class HTML(TextDisplayObject): |
|
380 | class HTML(TextDisplayObject): | |
381 |
|
381 | |||
382 | def _repr_html_(self): |
|
382 | def _repr_html_(self): | |
383 | return self.data |
|
383 | return self.data | |
384 |
|
384 | |||
385 | def __html__(self): |
|
385 | def __html__(self): | |
386 | """ |
|
386 | """ | |
387 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
387 | This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
388 | htmltag, etc) that this object is HTML and does not need things like |
|
388 | htmltag, etc) that this object is HTML and does not need things like | |
389 | special characters (<>&) escaped. |
|
389 | special characters (<>&) escaped. | |
390 | """ |
|
390 | """ | |
391 | return self._repr_html_() |
|
391 | return self._repr_html_() | |
392 |
|
392 | |||
393 |
|
393 | |||
394 | class Math(TextDisplayObject): |
|
394 | class Math(TextDisplayObject): | |
395 |
|
395 | |||
396 | def _repr_latex_(self): |
|
396 | def _repr_latex_(self): | |
397 | s = self.data.strip('$') |
|
397 | s = self.data.strip('$') | |
398 | return "$$%s$$" % s |
|
398 | return "$$%s$$" % s | |
399 |
|
399 | |||
400 |
|
400 | |||
401 | class Latex(TextDisplayObject): |
|
401 | class Latex(TextDisplayObject): | |
402 |
|
402 | |||
403 | def _repr_latex_(self): |
|
403 | def _repr_latex_(self): | |
404 | return self.data |
|
404 | return self.data | |
405 |
|
405 | |||
406 |
|
406 | |||
407 | class SVG(DisplayObject): |
|
407 | class SVG(DisplayObject): | |
408 |
|
408 | |||
409 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
409 | # wrap data in a property, which extracts the <svg> tag, discarding | |
410 | # document headers |
|
410 | # document headers | |
411 | _data = None |
|
411 | _data = None | |
412 |
|
412 | |||
413 | @property |
|
413 | @property | |
414 | def data(self): |
|
414 | def data(self): | |
415 | return self._data |
|
415 | return self._data | |
416 |
|
416 | |||
417 | @data.setter |
|
417 | @data.setter | |
418 | def data(self, svg): |
|
418 | def data(self, svg): | |
419 | if svg is None: |
|
419 | if svg is None: | |
420 | self._data = None |
|
420 | self._data = None | |
421 | return |
|
421 | return | |
422 | # parse into dom object |
|
422 | # parse into dom object | |
423 | from xml.dom import minidom |
|
423 | from xml.dom import minidom | |
424 | svg = cast_bytes_py2(svg) |
|
424 | svg = cast_bytes_py2(svg) | |
425 | x = minidom.parseString(svg) |
|
425 | x = minidom.parseString(svg) | |
426 | # get svg tag (should be 1) |
|
426 | # get svg tag (should be 1) | |
427 | found_svg = x.getElementsByTagName('svg') |
|
427 | found_svg = x.getElementsByTagName('svg') | |
428 | if found_svg: |
|
428 | if found_svg: | |
429 | svg = found_svg[0].toxml() |
|
429 | svg = found_svg[0].toxml() | |
430 | else: |
|
430 | else: | |
431 | # fallback on the input, trust the user |
|
431 | # fallback on the input, trust the user | |
432 | # but this is probably an error. |
|
432 | # but this is probably an error. | |
433 | pass |
|
433 | pass | |
434 | svg = cast_unicode(svg) |
|
434 | svg = cast_unicode(svg) | |
435 | self._data = svg |
|
435 | self._data = svg | |
436 |
|
436 | |||
437 | def _repr_svg_(self): |
|
437 | def _repr_svg_(self): | |
438 | return self.data |
|
438 | return self.data | |
439 |
|
439 | |||
440 |
|
440 | |||
441 | class JSON(TextDisplayObject): |
|
441 | class JSON(TextDisplayObject): | |
442 |
|
442 | |||
443 | def _repr_json_(self): |
|
443 | def _repr_json_(self): | |
444 | return self.data |
|
444 | return self.data | |
445 |
|
445 | |||
446 | css_t = """$("head").append($("<link/>").attr({ |
|
446 | css_t = """$("head").append($("<link/>").attr({ | |
447 | rel: "stylesheet", |
|
447 | rel: "stylesheet", | |
448 | type: "text/css", |
|
448 | type: "text/css", | |
449 | href: "%s" |
|
449 | href: "%s" | |
450 | })); |
|
450 | })); | |
451 | """ |
|
451 | """ | |
452 |
|
452 | |||
453 | lib_t1 = """$.getScript("%s", function () { |
|
453 | lib_t1 = """$.getScript("%s", function () { | |
454 | """ |
|
454 | """ | |
455 | lib_t2 = """}); |
|
455 | lib_t2 = """}); | |
456 | """ |
|
456 | """ | |
457 |
|
457 | |||
458 | class Javascript(TextDisplayObject): |
|
458 | class Javascript(TextDisplayObject): | |
459 |
|
459 | |||
460 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
460 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | |
461 | """Create a Javascript display object given raw data. |
|
461 | """Create a Javascript display object given raw data. | |
462 |
|
462 | |||
463 | When this object is returned by an expression or passed to the |
|
463 | When this object is returned by an expression or passed to the | |
464 | display function, it will result in the data being displayed |
|
464 | display function, it will result in the data being displayed | |
465 | in the frontend. If the data is a URL, the data will first be |
|
465 | in the frontend. If the data is a URL, the data will first be | |
466 | downloaded and then displayed. |
|
466 | downloaded and then displayed. | |
467 |
|
467 | |||
468 | In the Notebook, the containing element will be available as `element`, |
|
468 | In the Notebook, the containing element will be available as `element`, | |
469 | and jQuery will be available. The output area starts hidden, so if |
|
469 | and jQuery will be available. The output area starts hidden, so if | |
470 | the js appends content to `element` that should be visible, then |
|
470 | the js appends content to `element` that should be visible, then | |
471 | it must call `container.show()` to unhide the area. |
|
471 | it must call `container.show()` to unhide the area. | |
472 |
|
472 | |||
473 | Parameters |
|
473 | Parameters | |
474 | ---------- |
|
474 | ---------- | |
475 | data : unicode, str or bytes |
|
475 | data : unicode, str or bytes | |
476 | The Javascript source code or a URL to download it from. |
|
476 | The Javascript source code or a URL to download it from. | |
477 | url : unicode |
|
477 | url : unicode | |
478 | A URL to download the data from. |
|
478 | A URL to download the data from. | |
479 | filename : unicode |
|
479 | filename : unicode | |
480 | Path to a local file to load the data from. |
|
480 | Path to a local file to load the data from. | |
481 | lib : list or str |
|
481 | lib : list or str | |
482 | A sequence of Javascript library URLs to load asynchronously before |
|
482 | A sequence of Javascript library URLs to load asynchronously before | |
483 | running the source code. The full URLs of the libraries should |
|
483 | running the source code. The full URLs of the libraries should | |
484 | be given. A single Javascript library URL can also be given as a |
|
484 | be given. A single Javascript library URL can also be given as a | |
485 | string. |
|
485 | string. | |
486 | css: : list or str |
|
486 | css: : list or str | |
487 | A sequence of css files to load before running the source code. |
|
487 | A sequence of css files to load before running the source code. | |
488 | The full URLs of the css files should be given. A single css URL |
|
488 | The full URLs of the css files should be given. A single css URL | |
489 | can also be given as a string. |
|
489 | can also be given as a string. | |
490 | """ |
|
490 | """ | |
491 | if isinstance(lib, string_types): |
|
491 | if isinstance(lib, string_types): | |
492 | lib = [lib] |
|
492 | lib = [lib] | |
493 | elif lib is None: |
|
493 | elif lib is None: | |
494 | lib = [] |
|
494 | lib = [] | |
495 | if isinstance(css, string_types): |
|
495 | if isinstance(css, string_types): | |
496 | css = [css] |
|
496 | css = [css] | |
497 | elif css is None: |
|
497 | elif css is None: | |
498 | css = [] |
|
498 | css = [] | |
499 | if not isinstance(lib, (list,tuple)): |
|
499 | if not isinstance(lib, (list,tuple)): | |
500 | raise TypeError('expected sequence, got: %r' % lib) |
|
500 | raise TypeError('expected sequence, got: %r' % lib) | |
501 | if not isinstance(css, (list,tuple)): |
|
501 | if not isinstance(css, (list,tuple)): | |
502 | raise TypeError('expected sequence, got: %r' % css) |
|
502 | raise TypeError('expected sequence, got: %r' % css) | |
503 | self.lib = lib |
|
503 | self.lib = lib | |
504 | self.css = css |
|
504 | self.css = css | |
505 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
505 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | |
506 |
|
506 | |||
507 | def _repr_javascript_(self): |
|
507 | def _repr_javascript_(self): | |
508 | r = '' |
|
508 | r = '' | |
509 | for c in self.css: |
|
509 | for c in self.css: | |
510 | r += css_t % c |
|
510 | r += css_t % c | |
511 | for l in self.lib: |
|
511 | for l in self.lib: | |
512 | r += lib_t1 % l |
|
512 | r += lib_t1 % l | |
513 | r += self.data |
|
513 | r += self.data | |
514 | r += lib_t2*len(self.lib) |
|
514 | r += lib_t2*len(self.lib) | |
515 | return r |
|
515 | return r | |
516 |
|
516 | |||
517 | # constants for identifying png/jpeg data |
|
517 | # constants for identifying png/jpeg data | |
518 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
518 | _PNG = b'\x89PNG\r\n\x1a\n' | |
519 | _JPEG = b'\xff\xd8' |
|
519 | _JPEG = b'\xff\xd8' | |
520 |
|
520 | |||
521 | def _pngxy(data): |
|
521 | def _pngxy(data): | |
522 | """read the (width, height) from a PNG header""" |
|
522 | """read the (width, height) from a PNG header""" | |
523 | ihdr = data.index(b'IHDR') |
|
523 | ihdr = data.index(b'IHDR') | |
524 | # next 8 bytes are width/height |
|
524 | # next 8 bytes are width/height | |
525 | w4h4 = data[ihdr+4:ihdr+12] |
|
525 | w4h4 = data[ihdr+4:ihdr+12] | |
526 | return struct.unpack('>ii', w4h4) |
|
526 | return struct.unpack('>ii', w4h4) | |
527 |
|
527 | |||
528 | def _jpegxy(data): |
|
528 | def _jpegxy(data): | |
529 | """read the (width, height) from a JPEG header""" |
|
529 | """read the (width, height) from a JPEG header""" | |
530 | # adapted from http://www.64lines.com/jpeg-width-height |
|
530 | # adapted from http://www.64lines.com/jpeg-width-height | |
531 |
|
531 | |||
532 | idx = 4 |
|
532 | idx = 4 | |
533 | while True: |
|
533 | while True: | |
534 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
534 | block_size = struct.unpack('>H', data[idx:idx+2])[0] | |
535 | idx = idx + block_size |
|
535 | idx = idx + block_size | |
536 | if data[idx:idx+2] == b'\xFF\xC0': |
|
536 | if data[idx:idx+2] == b'\xFF\xC0': | |
537 | # found Start of Frame |
|
537 | # found Start of Frame | |
538 | iSOF = idx |
|
538 | iSOF = idx | |
539 | break |
|
539 | break | |
540 | else: |
|
540 | else: | |
541 | # read another block |
|
541 | # read another block | |
542 | idx += 2 |
|
542 | idx += 2 | |
543 |
|
543 | |||
544 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
544 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | |
545 | return w, h |
|
545 | return w, h | |
546 |
|
546 | |||
547 | class Image(DisplayObject): |
|
547 | class Image(DisplayObject): | |
548 |
|
548 | |||
549 | _read_flags = 'rb' |
|
549 | _read_flags = 'rb' | |
550 | _FMT_JPEG = u'jpeg' |
|
550 | _FMT_JPEG = u'jpeg' | |
551 | _FMT_PNG = u'png' |
|
551 | _FMT_PNG = u'png' | |
552 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
552 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] | |
553 |
|
553 | |||
554 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): |
|
554 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): | |
555 | """Create a PNG/JPEG image object given raw data. |
|
555 | """Create a PNG/JPEG image object given raw data. | |
556 |
|
556 | |||
557 | When this object is returned by an input cell or passed to the |
|
557 | When this object is returned by an input cell or passed to the | |
558 | display function, it will result in the image being displayed |
|
558 | display function, it will result in the image being displayed | |
559 | in the frontend. |
|
559 | in the frontend. | |
560 |
|
560 | |||
561 | Parameters |
|
561 | Parameters | |
562 | ---------- |
|
562 | ---------- | |
563 | data : unicode, str or bytes |
|
563 | data : unicode, str or bytes | |
564 | The raw image data or a URL or filename to load the data from. |
|
564 | The raw image data or a URL or filename to load the data from. | |
565 | This always results in embedded image data. |
|
565 | This always results in embedded image data. | |
566 | url : unicode |
|
566 | url : unicode | |
567 | A URL to download the data from. If you specify `url=`, |
|
567 | A URL to download the data from. If you specify `url=`, | |
568 | the image data will not be embedded unless you also specify `embed=True`. |
|
568 | the image data will not be embedded unless you also specify `embed=True`. | |
569 | filename : unicode |
|
569 | filename : unicode | |
570 | Path to a local file to load the data from. |
|
570 | Path to a local file to load the data from. | |
571 | Images from a file are always embedded. |
|
571 | Images from a file are always embedded. | |
572 | format : unicode |
|
572 | format : unicode | |
573 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
573 | The format of the image data (png/jpeg/jpg). If a filename or URL is given | |
574 | for format will be inferred from the filename extension. |
|
574 | for format will be inferred from the filename extension. | |
575 | embed : bool |
|
575 | embed : bool | |
576 | Should the image data be embedded using a data URI (True) or be |
|
576 | Should the image data be embedded using a data URI (True) or be | |
577 | loaded using an <img> tag. Set this to True if you want the image |
|
577 | loaded using an <img> tag. Set this to True if you want the image | |
578 | to be viewable later with no internet connection in the notebook. |
|
578 | to be viewable later with no internet connection in the notebook. | |
579 |
|
579 | |||
580 | Default is `True`, unless the keyword argument `url` is set, then |
|
580 | Default is `True`, unless the keyword argument `url` is set, then | |
581 | default value is `False`. |
|
581 | default value is `False`. | |
582 |
|
582 | |||
583 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
583 | Note that QtConsole is not able to display images if `embed` is set to `False` | |
584 | width : int |
|
584 | width : int | |
585 | Width to which to constrain the image in html |
|
585 | Width to which to constrain the image in html | |
586 | height : int |
|
586 | height : int | |
587 | Height to which to constrain the image in html |
|
587 | Height to which to constrain the image in html | |
588 | retina : bool |
|
588 | retina : bool | |
589 | Automatically set the width and height to half of the measured |
|
589 | Automatically set the width and height to half of the measured | |
590 | width and height. |
|
590 | width and height. | |
591 | This only works for embedded images because it reads the width/height |
|
591 | This only works for embedded images because it reads the width/height | |
592 | from image data. |
|
592 | from image data. | |
593 | For non-embedded images, you can just set the desired display width |
|
593 | For non-embedded images, you can just set the desired display width | |
594 | and height directly. |
|
594 | and height directly. | |
595 |
|
595 | |||
596 | Examples |
|
596 | Examples | |
597 | -------- |
|
597 | -------- | |
598 | # embedded image data, works in qtconsole and notebook |
|
598 | # embedded image data, works in qtconsole and notebook | |
599 | # when passed positionally, the first arg can be any of raw image data, |
|
599 | # when passed positionally, the first arg can be any of raw image data, | |
600 | # a URL, or a filename from which to load image data. |
|
600 | # a URL, or a filename from which to load image data. | |
601 | # The result is always embedding image data for inline images. |
|
601 | # The result is always embedding image data for inline images. | |
602 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
602 | Image('http://www.google.fr/images/srpr/logo3w.png') | |
603 | Image('/path/to/image.jpg') |
|
603 | Image('/path/to/image.jpg') | |
604 | Image(b'RAW_PNG_DATA...') |
|
604 | Image(b'RAW_PNG_DATA...') | |
605 |
|
605 | |||
606 | # Specifying Image(url=...) does not embed the image data, |
|
606 | # Specifying Image(url=...) does not embed the image data, | |
607 | # it only generates `<img>` tag with a link to the source. |
|
607 | # it only generates `<img>` tag with a link to the source. | |
608 | # This will not work in the qtconsole or offline. |
|
608 | # This will not work in the qtconsole or offline. | |
609 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
609 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | |
610 |
|
610 | |||
611 | """ |
|
611 | """ | |
612 | if filename is not None: |
|
612 | if filename is not None: | |
613 | ext = self._find_ext(filename) |
|
613 | ext = self._find_ext(filename) | |
614 | elif url is not None: |
|
614 | elif url is not None: | |
615 | ext = self._find_ext(url) |
|
615 | ext = self._find_ext(url) | |
616 | elif data is None: |
|
616 | elif data is None: | |
617 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
617 | raise ValueError("No image data found. Expecting filename, url, or data.") | |
618 | elif isinstance(data, string_types) and ( |
|
618 | elif isinstance(data, string_types) and ( | |
619 | data.startswith('http') or _safe_exists(data) |
|
619 | data.startswith('http') or _safe_exists(data) | |
620 | ): |
|
620 | ): | |
621 | ext = self._find_ext(data) |
|
621 | ext = self._find_ext(data) | |
622 | else: |
|
622 | else: | |
623 | ext = None |
|
623 | ext = None | |
624 |
|
624 | |||
625 | if ext is not None: |
|
625 | if ext is not None: | |
626 | format = ext.lower() |
|
626 | format = ext.lower() | |
627 | if ext == u'jpg' or ext == u'jpeg': |
|
627 | if ext == u'jpg' or ext == u'jpeg': | |
628 | format = self._FMT_JPEG |
|
628 | format = self._FMT_JPEG | |
629 | if ext == u'png': |
|
629 | if ext == u'png': | |
630 | format = self._FMT_PNG |
|
630 | format = self._FMT_PNG | |
631 | elif isinstance(data, bytes) and format == 'png': |
|
631 | elif isinstance(data, bytes) and format == 'png': | |
632 | # infer image type from image data header, |
|
632 | # infer image type from image data header, | |
633 | # only if format might not have been specified. |
|
633 | # only if format might not have been specified. | |
634 | if data[:2] == _JPEG: |
|
634 | if data[:2] == _JPEG: | |
635 | format = 'jpeg' |
|
635 | format = 'jpeg' | |
636 |
|
636 | |||
637 | self.format = unicode_type(format).lower() |
|
637 | self.format = unicode_type(format).lower() | |
638 | self.embed = embed if embed is not None else (url is None) |
|
638 | self.embed = embed if embed is not None else (url is None) | |
639 |
|
639 | |||
640 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
640 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | |
641 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
641 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) | |
642 | self.width = width |
|
642 | self.width = width | |
643 | self.height = height |
|
643 | self.height = height | |
644 | self.retina = retina |
|
644 | self.retina = retina | |
645 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
645 | super(Image, self).__init__(data=data, url=url, filename=filename) | |
646 |
|
646 | |||
647 | if retina: |
|
647 | if retina: | |
648 | self._retina_shape() |
|
648 | self._retina_shape() | |
649 |
|
649 | |||
650 | def _retina_shape(self): |
|
650 | def _retina_shape(self): | |
651 | """load pixel-doubled width and height from image data""" |
|
651 | """load pixel-doubled width and height from image data""" | |
652 | if not self.embed: |
|
652 | if not self.embed: | |
653 | return |
|
653 | return | |
654 | if self.format == 'png': |
|
654 | if self.format == 'png': | |
655 | w, h = _pngxy(self.data) |
|
655 | w, h = _pngxy(self.data) | |
656 | elif self.format == 'jpeg': |
|
656 | elif self.format == 'jpeg': | |
657 | w, h = _jpegxy(self.data) |
|
657 | w, h = _jpegxy(self.data) | |
658 | else: |
|
658 | else: | |
659 | # retina only supports png |
|
659 | # retina only supports png | |
660 | return |
|
660 | return | |
661 | self.width = w // 2 |
|
661 | self.width = w // 2 | |
662 | self.height = h // 2 |
|
662 | self.height = h // 2 | |
663 |
|
663 | |||
664 | def reload(self): |
|
664 | def reload(self): | |
665 | """Reload the raw data from file or URL.""" |
|
665 | """Reload the raw data from file or URL.""" | |
666 | if self.embed: |
|
666 | if self.embed: | |
667 | super(Image,self).reload() |
|
667 | super(Image,self).reload() | |
668 | if self.retina: |
|
668 | if self.retina: | |
669 | self._retina_shape() |
|
669 | self._retina_shape() | |
670 |
|
670 | |||
671 | def _repr_html_(self): |
|
671 | def _repr_html_(self): | |
672 | if not self.embed: |
|
672 | if not self.embed: | |
673 | width = height = '' |
|
673 | width = height = '' | |
674 | if self.width: |
|
674 | if self.width: | |
675 | width = ' width="%d"' % self.width |
|
675 | width = ' width="%d"' % self.width | |
676 | if self.height: |
|
676 | if self.height: | |
677 | height = ' height="%d"' % self.height |
|
677 | height = ' height="%d"' % self.height | |
678 | return u'<img src="%s"%s%s/>' % (self.url, width, height) |
|
678 | return u'<img src="%s"%s%s/>' % (self.url, width, height) | |
679 |
|
679 | |||
680 | def _data_and_metadata(self): |
|
680 | def _data_and_metadata(self): | |
681 | """shortcut for returning metadata with shape information, if defined""" |
|
681 | """shortcut for returning metadata with shape information, if defined""" | |
682 | md = {} |
|
682 | md = {} | |
683 | if self.width: |
|
683 | if self.width: | |
684 | md['width'] = self.width |
|
684 | md['width'] = self.width | |
685 | if self.height: |
|
685 | if self.height: | |
686 | md['height'] = self.height |
|
686 | md['height'] = self.height | |
687 | if md: |
|
687 | if md: | |
688 | return self.data, md |
|
688 | return self.data, md | |
689 | else: |
|
689 | else: | |
690 | return self.data |
|
690 | return self.data | |
691 |
|
691 | |||
692 | def _repr_png_(self): |
|
692 | def _repr_png_(self): | |
693 | if self.embed and self.format == u'png': |
|
693 | if self.embed and self.format == u'png': | |
694 | return self._data_and_metadata() |
|
694 | return self._data_and_metadata() | |
695 |
|
695 | |||
696 | def _repr_jpeg_(self): |
|
696 | def _repr_jpeg_(self): | |
697 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
697 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): | |
698 | return self._data_and_metadata() |
|
698 | return self._data_and_metadata() | |
699 |
|
699 | |||
700 | def _find_ext(self, s): |
|
700 | def _find_ext(self, s): | |
701 | return unicode_type(s.split('.')[-1].lower()) |
|
701 | return unicode_type(s.split('.')[-1].lower()) | |
702 |
|
702 | |||
703 |
|
703 | |||
704 | def clear_output(wait=False): |
|
704 | def clear_output(wait=False): | |
705 | """Clear the output of the current cell receiving output. |
|
705 | """Clear the output of the current cell receiving output. | |
706 |
|
706 | |||
707 | Parameters |
|
707 | Parameters | |
708 | ---------- |
|
708 | ---------- | |
709 | wait : bool [default: false] |
|
709 | wait : bool [default: false] | |
710 | Wait to clear the output until new output is available to replace it.""" |
|
710 | Wait to clear the output until new output is available to replace it.""" | |
711 | from IPython.core.interactiveshell import InteractiveShell |
|
711 | from IPython.core.interactiveshell import InteractiveShell | |
712 | if InteractiveShell.initialized(): |
|
712 | if InteractiveShell.initialized(): | |
713 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
713 | InteractiveShell.instance().display_pub.clear_output(wait) | |
714 | else: |
|
714 | else: | |
715 | from IPython.utils import io |
|
715 | from IPython.utils import io | |
716 | print('\033[2K\r', file=io.stdout, end='') |
|
716 | print('\033[2K\r', file=io.stdout, end='') | |
717 | io.stdout.flush() |
|
717 | io.stdout.flush() | |
718 | print('\033[2K\r', file=io.stderr, end='') |
|
718 | print('\033[2K\r', file=io.stderr, end='') | |
719 | io.stderr.flush() |
|
719 | io.stderr.flush() | |
720 |
|
720 | |||
721 |
|
721 | |||
722 | @skip_doctest |
|
722 | @skip_doctest | |
723 | def set_matplotlib_formats(*formats, **kwargs): |
|
723 | def set_matplotlib_formats(*formats, **kwargs): | |
724 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
724 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. | |
725 |
|
725 | |||
726 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
726 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: | |
727 |
|
727 | |||
728 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
728 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) | |
729 |
|
729 | |||
730 | To set this in your config files use the following:: |
|
730 | To set this in your config files use the following:: | |
731 |
|
731 | |||
732 | c.InlineBackend.figure_formats = {'pdf', 'png', 'svg'} |
|
732 | c.InlineBackend.figure_formats = {'pdf', 'png', 'svg'} | |
|
733 | c.InlineBackend.quality = 90 | |||
733 |
|
734 | |||
734 | Parameters |
|
735 | Parameters | |
735 | ---------- |
|
736 | ---------- | |
736 | *formats : list, tuple |
|
737 | *formats : list, tuple | |
737 | One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
738 | One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |
738 | quality : int |
|
739 | quality : int | |
739 | A percentage for the quality of JPEG figures. Defaults to 90. |
|
740 | A percentage for the quality of JPEG figures. Defaults to 90. | |
740 | """ |
|
741 | """ | |
741 | from IPython.core.interactiveshell import InteractiveShell |
|
742 | from IPython.core.interactiveshell import InteractiveShell | |
742 | from IPython.core.pylabtools import select_figure_formats |
|
743 | from IPython.core.pylabtools import select_figure_formats | |
743 | shell = InteractiveShell.instance() |
|
744 | shell = InteractiveShell.instance() | |
744 | select_figure_formats(shell, formats, quality=90) |
|
745 | select_figure_formats(shell, formats, quality=90) | |
745 |
|
746 | |||
746 | @skip_doctest |
|
747 | @skip_doctest | |
747 | def set_matplotlib_close(close): |
|
748 | def set_matplotlib_close(close): | |
748 | """Should the inline backend close all figures automatically. |
|
749 | """Should the inline backend close all figures automatically. | |
749 |
|
750 | |||
750 | By default, the inline backend used in the IPython Notebook will close all |
|
751 | By default, the inline backend used in the IPython Notebook will close all | |
751 | matplotlib figures automatically after each cell is run. This means that |
|
752 | matplotlib figures automatically after each cell is run. This means that | |
752 | plots in different cells won't interfere. Sometimes, you may want to make |
|
753 | plots in different cells won't interfere. Sometimes, you may want to make | |
753 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
754 | a plot in one cell and then refine it in later cells. This can be accomplished | |
754 | by:: |
|
755 | by:: | |
755 |
|
756 | |||
756 | In [1]: set_matplotlib_close(False) |
|
757 | In [1]: set_matplotlib_close(False) | |
757 |
|
758 | |||
758 | To set this in your config files use the following:: |
|
759 | To set this in your config files use the following:: | |
759 |
|
760 | |||
760 | c.InlineBackend.close_figures = False |
|
761 | c.InlineBackend.close_figures = False | |
761 |
|
762 | |||
762 | Parameters |
|
763 | Parameters | |
763 | ---------- |
|
764 | ---------- | |
764 | close : bool |
|
765 | close : bool | |
765 | Should all matplotlib figures be automatically closed after each cell is |
|
766 | Should all matplotlib figures be automatically closed after each cell is | |
766 | run? |
|
767 | run? | |
767 | """ |
|
768 | """ | |
768 | from IPython.kernel.zmq.pylab.backend_inline import InlineBackend |
|
769 | from IPython.kernel.zmq.pylab.backend_inline import InlineBackend | |
769 | ilbe = InlineBackend.instance() |
|
770 | ilbe = InlineBackend.instance() | |
770 | ilbe.close_figures = close |
|
771 | ilbe.close_figures = close | |
771 |
|
772 |
General Comments 0
You need to be logged in to leave comments.
Login now