display.py
1470 lines
| 48.4 KiB
| text/x-python
|
PythonLexer
|
r3278 | # -*- coding: utf-8 -*- | ||
|
r19557 | """Top-level display functions for displaying object in different formats.""" | ||
|
r3278 | |||
|
r19557 | # Copyright (c) IPython Development Team. | ||
# Distributed under the terms of the Modified BSD License. | ||||
|
r3278 | |||
|
r6422 | |||
|
r23854 | from binascii import b2a_hex, b2a_base64, hexlify | ||
|
r19557 | import json | ||
import mimetypes | ||||
|
r10050 | import os | ||
|
r10803 | import struct | ||
|
r22192 | import sys | ||
|
r19557 | import warnings | ||
|
r23746 | from copy import deepcopy | ||
|
r10050 | |||
|
r23666 | from IPython.utils.py3compat import cast_unicode | ||
|
r15126 | from IPython.testing.skipdoctest import skip_doctest | ||
|
r10449 | |||
|
r17121 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', | ||
|
r23849 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', | ||
|
r17121 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', | ||
|
r23859 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', | ||
'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats', | ||||
'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle', | ||||
'Video'] | ||||
|
r17121 | |||
|
r3278 | #----------------------------------------------------------------------------- | ||
|
r10050 | # utility functions | ||
#----------------------------------------------------------------------------- | ||||
def _safe_exists(path): | ||||
|
r10213 | """Check path, but don't let exceptions raise""" | ||
|
r10050 | try: | ||
return os.path.exists(path) | ||||
except Exception: | ||||
return False | ||||
|
r10448 | def _merge(d1, d2): | ||
"""Like update, but merges sub-dicts instead of clobbering at the top level. | ||||
|
r10490 | |||
|
r10448 | Updates d1 in-place | ||
""" | ||||
|
r10490 | |||
|
r10448 | if not isinstance(d2, dict) or not isinstance(d1, dict): | ||
return d2 | ||||
for key, value in d2.items(): | ||||
d1[key] = _merge(d1.get(key), value) | ||||
return d1 | ||||
|
r10449 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | ||
"""internal implementation of all display_foo methods | ||||
Parameters | ||||
---------- | ||||
mimetype : str | ||||
The mimetype to be published (e.g. 'image/png') | ||||
objs : tuple of objects | ||||
The Python objects to display, or if raw=True raw text data to | ||||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
metadata : dict (optional) | ||||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r10449 | """ | ||
|
r10450 | if metadata: | ||
metadata = {mimetype: metadata} | ||||
|
r10449 | if raw: | ||
|
r10450 | # turn list of pngdata into list of { 'image/png': pngdata } | ||
objs = [ {mimetype: obj} for obj in objs ] | ||||
display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | ||||
|
r10050 | #----------------------------------------------------------------------------- | ||
|
r3278 | # Main functions | ||
#----------------------------------------------------------------------------- | ||||
|
r23015 | # use * to indicate transient is keyword-only | ||
|
r23011 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): | ||
|
r17124 | """Publish data and metadata to all frontends. | ||
See the ``display_data`` message in the messaging documentation for | ||||
more details about this message type. | ||||
|
r23849 | Keys of data and metadata can be any mime-type. | ||
|
r17124 | |||
Parameters | ||||
---------- | ||||
data : dict | ||||
A dictionary having keys that are valid MIME types (like | ||||
'text/plain' or 'image/svg+xml') and values that are the data for | ||||
that MIME type. The data itself must be a JSON'able data | ||||
structure. Minimally all data should have the 'text/plain' data, | ||||
which can be displayed by all frontends. If more than the plain | ||||
text is given, it is up to the frontend to decide which | ||||
representation to use. | ||||
metadata : dict | ||||
A dictionary for metadata related to the data. This can contain | ||||
arbitrary key, value pairs that frontends can use to interpret | ||||
the data. mime-type keys matching those in data can be used | ||||
to specify metadata about particular representations. | ||||
source : str, deprecated | ||||
Unused. | ||||
|
r23015 | transient : dict, keyword-only | ||
|
r23010 | A dictionary of transient data, such as display_id. | ||
|
r17124 | """ | ||
from IPython.core.interactiveshell import InteractiveShell | ||||
|
r23010 | |||
display_pub = InteractiveShell.instance().display_pub | ||||
# only pass transient if supplied, | ||||
# to avoid errors with older ipykernel. | ||||
# TODO: We could check for ipykernel version and provide a detailed upgrade message. | ||||
if transient: | ||||
kwargs['transient'] = transient | ||||
display_pub.publish( | ||||
|
r17124 | data=data, | ||
metadata=metadata, | ||||
|
r22999 | **kwargs | ||
|
r17124 | ) | ||
|
r23012 | |||
def _new_id(): | ||||
"""Generate a new random text id with urandom""" | ||||
return b2a_hex(os.urandom(16)).decode('ascii') | ||||
|
r23011 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): | ||
|
r3278 | """Display a Python object in all frontends. | ||
By default all representations will be computed and sent to the frontends. | ||||
Frontends can decide which representation is used and how. | ||||
|
r23712 | In terminal IPython this will be similar to using :func:`print`, for use in richer | ||
|
r23711 | frontends see Jupyter notebook examples with rich display logic. | ||
|
r3278 | Parameters | ||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
The Python objects to display. | ||||
|
r10450 | raw : bool, optional | ||
Are the objects to be displayed already mimetype-keyed dicts of raw display data, | ||||
or Python objects that need to be formatted before display? [default: False] | ||||
|
r23712 | include : list, tuple or set, optional | ||
|
r3278 | A list of format type strings (MIME types) to include in the | ||
format data dict. If this is set *only* the format types included | ||||
in this list will be computed. | ||||
|
r23712 | exclude : list, tuple or set, optional | ||
|
r10213 | A list of format type strings (MIME types) to exclude in the format | ||
|
r3278 | data dict. If this is set all format types will be computed, | ||
except for those included in this argument. | ||||
|
r10448 | metadata : dict, optional | ||
A dictionary of metadata to associate with the output. | ||||
mime-type keys in this dictionary will be associated with the individual | ||||
representation formats, if they exist. | ||||
|
r22999 | transient : dict, optional | ||
A dictionary of transient data to associate with the output. | ||||
Data in this dict should not be persisted to files (e.g. notebooks). | ||||
|
r23712 | display_id : str, bool optional | ||
|
r22999 | Set an id for the display. | ||
This id can be used for updating this display area later via update_display. | ||||
|
r23712 | If given as `True`, generate a new `display_id` | ||
|
r23011 | kwargs: additional keyword-args, optional | ||
Additional keyword-arguments are passed through to the display publisher. | ||||
|
r23711 | |||
|
r23012 | Returns | ||
------- | ||||
|
r23711 | |||
|
r23012 | handle: DisplayHandle | ||
|
r23712 | Returns a handle on updatable displays for use with :func:`update_display`, | ||
if `display_id` is given. Returns :any:`None` if no `display_id` is given | ||||
(default). | ||||
|
r23711 | |||
Examples | ||||
-------- | ||||
>>> class Json(object): | ||||
... def __init__(self, json): | ||||
... self.json = json | ||||
... def _repr_pretty_(self, pp, cycle): | ||||
... import json | ||||
... pp.text(json.dumps(self.json, indent=2)) | ||||
... def __repr__(self): | ||||
... return str(self.json) | ||||
... | ||||
>>> d = Json({1:2, 3: {4:5}}) | ||||
>>> print(d) | ||||
{1: 2, 3: {4: 5}} | ||||
>>> display(d) | ||||
{ | ||||
"1": 2, | ||||
"3": { | ||||
"4": 5 | ||||
} | ||||
} | ||||
>>> def int_formatter(integer, pp, cycle): | ||||
... pp.text('I'*integer) | ||||
>>> plain = get_ipython().display_formatter.formatters['text/plain'] | ||||
>>> plain.for_type(int, int_formatter) | ||||
<function _repr_pprint at 0x...> | ||||
>>> display(7-5) | ||||
II | ||||
>>> del plain.type_printers[int] | ||||
>>> display(7-5) | ||||
2 | ||||
See Also | ||||
-------- | ||||
|
r23712 | :func:`update_display` | ||
|
r23711 | |||
Notes | ||||
----- | ||||
In Python, objects can declare their textual representation using the | ||||
`__repr__` method. IPython expands on this idea and allows objects to declare | ||||
other, rich representations including: | ||||
- HTML | ||||
- JSON | ||||
- PNG | ||||
- JPEG | ||||
- SVG | ||||
- LaTeX | ||||
A single object can declare some or all of these representations; all are | ||||
handled by IPython's display system. | ||||
The main idea of the first approach is that you have to implement special | ||||
display methods when you define your class, one for each representation you | ||||
want to use. Here is a list of the names of the special methods and the | ||||
values they must return: | ||||
|
r24621 | - `_repr_html_`: return raw HTML as a string, or a tuple (see below). | ||
- `_repr_json_`: return a JSONable dict, or a tuple (see below). | ||||
- `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). | ||||
- `_repr_png_`: return raw PNG data, or a tuple (see below). | ||||
- `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). | ||||
- `_repr_latex_`: return LaTeX commands in a string surrounded by "$", | ||||
or a tuple (see below). | ||||
|
r23711 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping | ||
|
r23849 | from all mimetypes to data. | ||
Use this for any mime-type not listed above. | ||||
|
r23711 | |||
|
r24621 | The above functions may also return the object's metadata alonside the | ||
data. If the metadata is available, the functions will return a tuple | ||||
containing the data and metadata, in that order. If there is no metadata | ||||
available, then the functions will return the data only. | ||||
|
r23711 | When you are directly writing your own classes, you can adapt them for | ||
display in IPython by following the above approach. But in practice, you | ||||
often need to work with existing classes that you can't easily modify. | ||||
|
r24041 | You can refer to the documentation on integrating with the display system in | ||
order to register custom formatters for already existing types | ||||
(:ref:`integrating_rich_display`). | ||||
|
r23711 | |||
|
r23712 | .. versionadded:: 5.4 display available without import | ||
.. versionadded:: 6.1 display available without import | ||||
Since IPython 5.4 and 6.1 :func:`display` is automatically made available to | ||||
the user without import. If you are using display in a document that might | ||||
be used in a pure python context or with older version of IPython, use the | ||||
|
r23711 | following import at the top of your file:: | ||
from IPython.display import display | ||||
|
r3278 | """ | ||
|
r23744 | from IPython.core.interactiveshell import InteractiveShell | ||
|
r23745 | if not InteractiveShell.initialized(): | ||
|
r23744 | # Directly print objects. | ||
print(*objs) | ||||
return | ||||
|
r22999 | raw = kwargs.pop('raw', False) | ||
|
r23011 | if transient is None: | ||
transient = {} | ||||
|
r23746 | if metadata is None: | ||
metadata={} | ||||
|
r23011 | if display_id: | ||
|
r23711 | if display_id is True: | ||
|
r23012 | display_id = _new_id() | ||
|
r23011 | transient['display_id'] = display_id | ||
|
r22999 | if kwargs.get('update') and 'display_id' not in transient: | ||
raise TypeError('display_id required for update_display') | ||||
|
r23011 | if transient: | ||
kwargs['transient'] = transient | ||||
|
r4872 | |||
|
r14233 | if not raw: | ||
format = InteractiveShell.instance().display_formatter.format | ||||
for obj in objs: | ||||
|
r14795 | if raw: | ||
|
r22999 | publish_display_data(data=obj, metadata=metadata, **kwargs) | ||
|
r14795 | else: | ||
format_dict, md_dict = format(obj, include=include, exclude=exclude) | ||||
|
r19381 | if not format_dict: | ||
# nothing to display (e.g. _ipython_display_ took over) | ||||
continue | ||||
|
r14795 | if metadata: | ||
# kwarg-specified metadata gets precedence | ||||
_merge(md_dict, metadata) | ||||
|
r23012 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) | ||
if display_id: | ||||
return DisplayHandle(display_id) | ||||
|
r22999 | |||
|
r23015 | # use * for keyword-only display_id arg | ||
|
r23012 | def update_display(obj, *, display_id, **kwargs): | ||
"""Update an existing display by id | ||||
|
r23011 | |||
Parameters | ||||
---------- | ||||
obj: | ||||
The object with which to update the display | ||||
display_id: keyword-only | ||||
The id of the display to update | ||||
|
r23712 | |||
See Also | ||||
-------- | ||||
:func:`display` | ||||
|
r23011 | """ | ||
|
r22999 | kwargs['update'] = True | ||
|
r23012 | display(obj, display_id=display_id, **kwargs) | ||
class DisplayHandle(object): | ||||
"""A handle on an updatable display | ||||
|
r23011 | |||
|
r23712 | Call `.update(obj)` to display a new object. | ||
|
r23012 | |||
|
r23712 | Call `.display(obj`) to add a new instance of this display, | ||
|
r23012 | and update existing instances. | ||
|
r23712 | |||
See Also | ||||
-------- | ||||
:func:`display`, :func:`update_display` | ||||
|
r23012 | """ | ||
def __init__(self, display_id=None): | ||||
if display_id is None: | ||||
display_id = _new_id() | ||||
self.display_id = display_id | ||||
def __repr__(self): | ||||
return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) | ||||
def display(self, obj, **kwargs): | ||||
"""Make a new display with my id, updating existing instances. | ||||
Parameters | ||||
---------- | ||||
obj: | ||||
object to display | ||||
**kwargs: | ||||
additional keyword arguments passed to display | ||||
""" | ||||
display(obj, display_id=self.display_id, **kwargs) | ||||
def update(self, obj, **kwargs): | ||||
"""Update existing displays with my id | ||||
Parameters | ||||
---------- | ||||
obj: | ||||
object to display | ||||
**kwargs: | ||||
additional keyword arguments passed to update_display | ||||
""" | ||||
update_display(obj, display_id=self.display_id, **kwargs) | ||||
|
r3279 | |||
|
r10448 | |||
def display_pretty(*objs, **kwargs): | ||||
"""Display the pretty (default) representation of an object. | ||||
Parameters | ||||
---------- | ||||
objs : tuple of objects | ||||
The Python objects to display, or if raw=True raw text data to | ||||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
metadata : dict (optional) | ||||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r10448 | """ | ||
_display_mimetype('text/plain', objs, **kwargs) | ||||
|
r3279 | |||
|
r4526 | def display_html(*objs, **kwargs): | ||
|
r3278 | """Display the HTML representation of an object. | ||
|
r22947 | |||
|
r21995 | Note: If raw=False and the object does not have a HTML | ||
representation, no HTML will be shown. | ||||
|
r3278 | |||
Parameters | ||||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
|
r4528 | The Python objects to display, or if raw=True raw HTML data to | ||
|
r4526 | display. | ||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r4526 | """ | ||
|
r10448 | _display_mimetype('text/html', objs, **kwargs) | ||
|
r3278 | |||
|
r16364 | def display_markdown(*objs, **kwargs): | ||
"""Displays the Markdown representation of an object. | ||||
Parameters | ||||
---------- | ||||
objs : tuple of objects | ||||
The Python objects to display, or if raw=True raw markdown data to | ||||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
metadata : dict (optional) | ||||
Metadata to be associated with the specific mimetype output. | ||||
""" | ||||
_display_mimetype('text/markdown', objs, **kwargs) | ||||
|
r4526 | def display_svg(*objs, **kwargs): | ||
|
r3278 | """Display the SVG representation of an object. | ||
Parameters | ||||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
|
r4526 | The Python objects to display, or if raw=True raw svg data to | ||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r3278 | """ | ||
|
r10448 | _display_mimetype('image/svg+xml', objs, **kwargs) | ||
|
r3278 | |||
|
r4526 | def display_png(*objs, **kwargs): | ||
|
r3278 | """Display the PNG representation of an object. | ||
Parameters | ||||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
|
r4526 | The Python objects to display, or if raw=True raw png data to | ||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r3278 | """ | ||
|
r10448 | _display_mimetype('image/png', objs, **kwargs) | ||
|
r3278 | |||
|
r4528 | def display_jpeg(*objs, **kwargs): | ||
"""Display the JPEG representation of an object. | ||||
Parameters | ||||
---------- | ||||
objs : tuple of objects | ||||
The Python objects to display, or if raw=True raw JPEG data to | ||||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r4528 | """ | ||
|
r10448 | _display_mimetype('image/jpeg', objs, **kwargs) | ||
|
r4528 | |||
|
r4526 | def display_latex(*objs, **kwargs): | ||
|
r3278 | """Display the LaTeX representation of an object. | ||
Parameters | ||||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
|
r4526 | The Python objects to display, or if raw=True raw latex data to | ||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r3278 | """ | ||
|
r10448 | _display_mimetype('text/latex', objs, **kwargs) | ||
|
r3278 | |||
|
r4526 | def display_json(*objs, **kwargs): | ||
|
r3278 | """Display the JSON representation of an object. | ||
|
r10212 | |||
|
r8086 | Note that not many frontends support displaying JSON. | ||
|
r3278 | |||
Parameters | ||||
---------- | ||||
|
r3288 | objs : tuple of objects | ||
|
r4526 | The Python objects to display, or if raw=True raw json data to | ||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r3278 | """ | ||
|
r10448 | _display_mimetype('application/json', objs, **kwargs) | ||
|
r3278 | |||
|
r4526 | def display_javascript(*objs, **kwargs): | ||
|
r3878 | """Display the Javascript representation of an object. | ||
|
r3278 | |||
|
r3878 | Parameters | ||
---------- | ||||
objs : tuple of objects | ||||
|
r4526 | The Python objects to display, or if raw=True raw javascript data to | ||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
|
r10448 | metadata : dict (optional) | ||
|
r10450 | Metadata to be associated with the specific mimetype output. | ||
|
r3878 | """ | ||
|
r10448 | _display_mimetype('application/javascript', objs, **kwargs) | ||
|
r4526 | |||
|
r15121 | |||
def display_pdf(*objs, **kwargs): | ||||
"""Display the PDF representation of an object. | ||||
Parameters | ||||
---------- | ||||
objs : tuple of objects | ||||
The Python objects to display, or if raw=True raw javascript data to | ||||
display. | ||||
raw : bool | ||||
Are the data objects raw data or Python objects that need to be | ||||
formatted before display? [default: False] | ||||
metadata : dict (optional) | ||||
Metadata to be associated with the specific mimetype output. | ||||
""" | ||||
_display_mimetype('application/pdf', objs, **kwargs) | ||||
|
r4526 | #----------------------------------------------------------------------------- | ||
# Smart classes | ||||
#----------------------------------------------------------------------------- | ||||
class DisplayObject(object): | ||||
"""An object that wraps data to be displayed.""" | ||||
|
r4528 | _read_flags = 'r' | ||
|
r16396 | _show_mem_addr = False | ||
|
r23746 | metadata = None | ||
|
r4528 | |||
|
r23746 | def __init__(self, data=None, url=None, filename=None, metadata=None): | ||
|
r4528 | """Create a display object given raw data. | ||
|
r4526 | |||
When this object is returned by an expression or passed to the | ||||
display function, it will result in the data being displayed | ||||
in the frontend. The MIME type of the data should match the | ||||
subclasses used, so the Png subclass should be used for 'image/png' | ||||
data. If the data is a URL, the data will first be downloaded | ||||
|
r4872 | and then displayed. If | ||
|
r4526 | |||
Parameters | ||||
---------- | ||||
data : unicode, str or bytes | ||||
|
r10050 | The raw data or a URL or file to load the data from | ||
|
r4528 | url : unicode | ||
A URL to download the data from. | ||||
filename : unicode | ||||
Path to a local file to load the data from. | ||||
|
r23746 | metadata : dict | ||
Dict of metadata associated to be the object when displayed | ||||
|
r4526 | """ | ||
|
r23037 | if data is not None and isinstance(data, str): | ||
|
r10050 | if data.startswith('http') and url is None: | ||
url = data | ||||
filename = None | ||||
data = None | ||||
elif _safe_exists(data) and filename is None: | ||||
url = None | ||||
filename = data | ||||
data = None | ||||
|
r10212 | |||
|
r10050 | self.data = data | ||
self.url = url | ||||
|
r23044 | self.filename = filename | ||
|
r10212 | |||
|
r23746 | if metadata is not None: | ||
self.metadata = metadata | ||||
elif self.metadata is None: | ||||
self.metadata = {} | ||||
|
r4528 | self.reload() | ||
|
r14153 | self._check_data() | ||
|
r16396 | |||
def __repr__(self): | ||||
if not self._show_mem_addr: | ||||
cls = self.__class__ | ||||
r = "<%s.%s object>" % (cls.__module__, cls.__name__) | ||||
else: | ||||
r = super(DisplayObject, self).__repr__() | ||||
return r | ||||
|
r14153 | def _check_data(self): | ||
"""Override in subclasses if there's something to check.""" | ||||
pass | ||||
|
r4528 | |||
|
r23746 | def _data_and_metadata(self): | ||
"""shortcut for returning metadata with shape information, if defined""" | ||||
if self.metadata: | ||||
return self.data, deepcopy(self.metadata) | ||||
else: | ||||
return self.data | ||||
|
r4528 | def reload(self): | ||
"""Reload the raw data from file or URL.""" | ||||
if self.filename is not None: | ||||
with open(self.filename, self._read_flags) as f: | ||||
self.data = f.read() | ||||
elif self.url is not None: | ||||
try: | ||||
|
r23075 | # Deferred import | ||
from urllib.request import urlopen | ||||
|
r13640 | response = urlopen(self.url) | ||
|
r4528 | self.data = response.read() | ||
|
r4684 | # extract encoding from header, if there is one: | ||
encoding = None | ||||
for sub in response.headers['content-type'].split(';'): | ||||
sub = sub.strip() | ||||
if sub.startswith('charset'): | ||||
encoding = sub.split('=')[-1].strip() | ||||
break | ||||
# decode data, if an encoding was specified | ||||
if encoding: | ||||
self.data = self.data.decode(encoding, 'replace') | ||||
|
r4528 | except: | ||
self.data = None | ||||
|
r4526 | |||
|
r14153 | class TextDisplayObject(DisplayObject): | ||
"""Validate that display data is text""" | ||||
def _check_data(self): | ||||
|
r23037 | if self.data is not None and not isinstance(self.data, str): | ||
|
r14159 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | ||
|
r14153 | |||
class Pretty(TextDisplayObject): | ||||
|
r4526 | |||
|
r23729 | def _repr_pretty_(self, pp, cycle): | ||
return pp.text(self.data) | ||||
|
r4526 | |||
|
r14153 | class HTML(TextDisplayObject): | ||
|
r4526 | |||
|
r24619 | def __init__(self, data=None, url=None, filename=None, metadata=None): | ||
|
r24654 | def warn(): | ||
if not data: | ||||
return False | ||||
# | ||||
# Avoid calling lower() on the entire data, because it could be a | ||||
# long string and we're only interested in its beginning and end. | ||||
# | ||||
prefix = data[:10].lower() | ||||
suffix = data[-10:].lower() | ||||
return prefix.startswith("<iframe ") and suffix.endswith("</iframe>") | ||||
if warn(): | ||||
|
r24619 | warnings.warn("Consider using IPython.display.IFrame instead") | ||
super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata) | ||||
|
r4526 | def _repr_html_(self): | ||
|
r24301 | return self._data_and_metadata() | ||
|
r4526 | |||
|
r10490 | def __html__(self): | ||
""" | ||||
This method exists to inform other HTML-using modules (e.g. Markupsafe, | ||||
htmltag, etc) that this object is HTML and does not need things like | ||||
special characters (<>&) escaped. | ||||
""" | ||||
return self._repr_html_() | ||||
|
r4526 | |||
|
r16364 | class Markdown(TextDisplayObject): | ||
def _repr_markdown_(self): | ||||
|
r24301 | return self._data_and_metadata() | ||
|
r16364 | |||
|
r14153 | class Math(TextDisplayObject): | ||
|
r4526 | |||
def _repr_latex_(self): | ||||
|
r24780 | s = r"$\displaystyle %s$" % self.data.strip('$') | ||
|
r24301 | if self.metadata: | ||
return s, deepcopy(self.metadata) | ||||
else: | ||||
return s | ||||
|
r6065 | |||
|
r14153 | class Latex(TextDisplayObject): | ||
|
r6065 | |||
def _repr_latex_(self): | ||||
|
r24301 | return self._data_and_metadata() | ||
|
r4526 | |||
|
r4528 | class SVG(DisplayObject): | ||
|
r10212 | |||
|
r23026 | _read_flags = 'rb' | ||
|
r5671 | # wrap data in a property, which extracts the <svg> tag, discarding | ||
# document headers | ||||
_data = None | ||||
|
r10212 | |||
|
r5671 | @property | ||
def data(self): | ||||
return self._data | ||||
|
r10212 | |||
|
r5671 | @data.setter | ||
def data(self, svg): | ||||
if svg is None: | ||||
self._data = None | ||||
return | ||||
# parse into dom object | ||||
|
r9390 | from xml.dom import minidom | ||
|
r5671 | x = minidom.parseString(svg) | ||
# get svg tag (should be 1) | ||||
found_svg = x.getElementsByTagName('svg') | ||||
if found_svg: | ||||
svg = found_svg[0].toxml() | ||||
else: | ||||
# fallback on the input, trust the user | ||||
# but this is probably an error. | ||||
pass | ||||
|
r11535 | svg = cast_unicode(svg) | ||
|
r5671 | self._data = svg | ||
|
r23746 | |||
|
r4526 | def _repr_svg_(self): | ||
|
r23746 | return self._data_and_metadata() | ||
|
r4526 | |||
|
r23856 | class ProgressBar(DisplayObject): | ||
|
r23854 | """Progressbar supports displaying a progressbar like element | ||
""" | ||||
def __init__(self, total): | ||||
"""Creates a new progressbar | ||||
Parameters | ||||
---------- | ||||
total : int | ||||
|
r23859 | maximum size of the progressbar | ||
|
r23854 | """ | ||
self.total = total | ||||
self._progress = 0 | ||||
|
r23860 | self.html_width = '60ex' | ||
self.text_width = 60 | ||||
self._display_id = hexlify(os.urandom(8)).decode('ascii') | ||||
def __repr__(self): | ||||
fraction = self.progress / self.total | ||||
filled = '=' * int(fraction * self.text_width) | ||||
rest = ' ' * (self.text_width - len(filled)) | ||||
return '[{}{}] {}/{}'.format( | ||||
filled, rest, | ||||
self.progress, self.total, | ||||
) | ||||
|
r23854 | |||
def _repr_html_(self): | ||||
|
r23860 | return "<progress style='width:{}' max='{}' value='{}'></progress>".format( | ||
self.html_width, self.total, self.progress) | ||||
|
r23854 | |||
def display(self): | ||||
display(self, display_id=self._display_id) | ||||
def update(self): | ||||
display(self, display_id=self._display_id, update=True) | ||||
@property | ||||
def progress(self): | ||||
return self._progress | ||||
@progress.setter | ||||
def progress(self, value): | ||||
self._progress = value | ||||
self.update() | ||||
|
r4526 | |||
|
r23943 | def __iter__(self): | ||
self.display() | ||||
self._progress = -1 # First iteration is 0 | ||||
return self | ||||
def __next__(self): | ||||
"""Returns current value and increments display by one.""" | ||||
self.progress += 1 | ||||
if self.progress < self.total: | ||||
return self.progress | ||||
else: | ||||
raise StopIteration() | ||||
|
r19557 | class JSON(DisplayObject): | ||
"""JSON expects a JSON-able dict or list | ||||
|
r22947 | |||
|
r19557 | not an already-serialized JSON string. | ||
|
r22947 | |||
|
r19557 | Scalar types (None, number, string) are not allowed, only dict or list containers. | ||
""" | ||||
# wrap data in a property, which warns about passing already-serialized JSON | ||||
_data = None | ||||
|
r24412 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs): | ||
|
r22947 | """Create a JSON display object given raw data. | ||
Parameters | ||||
---------- | ||||
data : dict or list | ||||
JSON data to display. Not an already-serialized JSON string. | ||||
Scalar types (None, number, string) are not allowed, only dict | ||||
or list containers. | ||||
url : unicode | ||||
A URL to download the data from. | ||||
filename : unicode | ||||
Path to a local file to load the data from. | ||||
expanded : boolean | ||||
Metadata to control whether a JSON display component is expanded. | ||||
metadata: dict | ||||
Specify extra metadata to attach to the json display object. | ||||
|
r24412 | root : str | ||
The name of the root element of the JSON tree | ||||
|
r22947 | """ | ||
|
r24412 | self.metadata = { | ||
'expanded': expanded, | ||||
'root': root, | ||||
} | ||||
|
r23501 | if metadata: | ||
self.metadata.update(metadata) | ||||
|
r23503 | if kwargs: | ||
self.metadata.update(kwargs) | ||||
|
r22947 | super(JSON, self).__init__(data=data, url=url, filename=filename) | ||
|
r19557 | def _check_data(self): | ||
if self.data is not None and not isinstance(self.data, (dict, list)): | ||||
raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) | ||||
@property | ||||
def data(self): | ||||
return self._data | ||||
|
r22947 | |||
|
r19557 | @data.setter | ||
def data(self, data): | ||||
|
r23037 | if isinstance(data, str): | ||
|
r23395 | if getattr(self, 'filename', None) is None: | ||
|
r23393 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") | ||
|
r19557 | data = json.loads(data) | ||
self._data = data | ||||
|
r4526 | |||
|
r22947 | def _data_and_metadata(self): | ||
|
r23501 | return self.data, self.metadata | ||
|
r22947 | |||
|
r4526 | def _repr_json_(self): | ||
|
r22947 | return self._data_and_metadata() | ||
|
r4526 | |||
|
r24470 | _css_t = """var link = document.createElement("link"); | ||
link.ref = "stylesheet"; | ||||
link.type = "text/css"; | ||||
link.href = "%s"; | ||||
document.head.appendChild(link); | ||||
|
r6120 | """ | ||
|
r24479 | _lib_t1 = """new Promise(function(resolve, reject) { | ||
var script = document.createElement("script"); | ||||
script.onload = resolve; | ||||
script.onerror = reject; | ||||
|
r24470 | script.src = "%s"; | ||
|
r24479 | document.head.appendChild(script); | ||
}).then(() => { | ||||
|
r6120 | """ | ||
|
r4526 | |||
|
r24479 | _lib_t2 = """ | ||
});""" | ||||
|
r24470 | |||
|
r23501 | class GeoJSON(JSON): | ||
|
r23404 | """GeoJSON expects JSON-able dict | ||
|
r23312 | |||
|
r23404 | not an already-serialized JSON string. | ||
Scalar types (None, number, string) are not allowed, only dict containers. | ||||
""" | ||||
|
r23501 | def __init__(self, *args, **kwargs): | ||
|
r23404 | """Create a GeoJSON display object given raw data. | ||
Parameters | ||||
---------- | ||||
data : dict or list | ||||
VegaLite data. Not an already-serialized JSON string. | ||||
Scalar types (None, number, string) are not allowed, only dict | ||||
or list containers. | ||||
url_template : string | ||||
Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template | ||||
layer_options : dict | ||||
Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options | ||||
url : unicode | ||||
A URL to download the data from. | ||||
filename : unicode | ||||
Path to a local file to load the data from. | ||||
metadata: dict | ||||
Specify extra metadata to attach to the json display object. | ||||
|
r23407 | |||
Examples | ||||
-------- | ||||
The following will display an interactive map of Mars with a point of | ||||
interest on frontend that do support GeoJSON display. | ||||
>>> from IPython.display import GeoJSON | ||||
>>> GeoJSON(data={ | ||||
... "type": "Feature", | ||||
... "geometry": { | ||||
... "type": "Point", | ||||
... "coordinates": [-81.327, 296.038] | ||||
... } | ||||
... }, | ||||
... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", | ||||
... layer_options={ | ||||
... "basemap_id": "celestia_mars-shaded-16k_global", | ||||
... "attribution" : "Celestia/praesepe", | ||||
... "minZoom" : 0, | ||||
... "maxZoom" : 18, | ||||
... }) | ||||
<IPython.core.display.GeoJSON object> | ||||
In the terminal IPython, you will only see the text representation of | ||||
the GeoJSON object. | ||||
|
r23404 | """ | ||
|
r23501 | super(GeoJSON, self).__init__(*args, **kwargs) | ||
|
r23312 | |||
def _ipython_display_(self): | ||||
bundle = { | ||||
'application/geo+json': self.data, | ||||
|
r23501 | 'text/plain': '<IPython.display.GeoJSON object>' | ||
|
r23312 | } | ||
|
r23404 | metadata = { | ||
|
r23501 | 'application/geo+json': self.metadata | ||
|
r23404 | } | ||
display(bundle, metadata=metadata, raw=True) | ||||
|
r23312 | |||
|
r14153 | class Javascript(TextDisplayObject): | ||
|
r4526 | |||
|
r6120 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | ||
"""Create a Javascript display object given raw data. | ||||
When this object is returned by an expression or passed to the | ||||
display function, it will result in the data being displayed | ||||
in the frontend. If the data is a URL, the data will first be | ||||
|
r10212 | downloaded and then displayed. | ||
|
r6425 | In the Notebook, the containing element will be available as `element`, | ||
|
r17002 | and jQuery will be available. Content appended to `element` will be | ||
|
r22947 | visible in the output area. | ||
|
r6120 | |||
Parameters | ||||
---------- | ||||
data : unicode, str or bytes | ||||
The Javascript source code or a URL to download it from. | ||||
url : unicode | ||||
A URL to download the data from. | ||||
filename : unicode | ||||
Path to a local file to load the data from. | ||||
lib : list or str | ||||
A sequence of Javascript library URLs to load asynchronously before | ||||
running the source code. The full URLs of the libraries should | ||||
be given. A single Javascript library URL can also be given as a | ||||
string. | ||||
css: : list or str | ||||
A sequence of css files to load before running the source code. | ||||
|
r10212 | The full URLs of the css files should be given. A single css URL | ||
|
r6120 | can also be given as a string. | ||
""" | ||||
|
r23037 | if isinstance(lib, str): | ||
|
r6120 | lib = [lib] | ||
elif lib is None: | ||||
lib = [] | ||||
|
r23037 | if isinstance(css, str): | ||
|
r6120 | css = [css] | ||
elif css is None: | ||||
css = [] | ||||
if not isinstance(lib, (list,tuple)): | ||||
raise TypeError('expected sequence, got: %r' % lib) | ||||
if not isinstance(css, (list,tuple)): | ||||
raise TypeError('expected sequence, got: %r' % css) | ||||
self.lib = lib | ||||
self.css = css | ||||
|
r23816 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | ||
|
r6120 | |||
|
r4526 | def _repr_javascript_(self): | ||
|
r6120 | r = '' | ||
for c in self.css: | ||||
|
r23524 | r += _css_t % c | ||
|
r6120 | for l in self.lib: | ||
|
r23524 | r += _lib_t1 % l | ||
|
r6120 | r += self.data | ||
|
r23524 | r += _lib_t2*len(self.lib) | ||
|
r6120 | return r | ||
|
r4526 | |||
|
r10049 | # constants for identifying png/jpeg data | ||
_PNG = b'\x89PNG\r\n\x1a\n' | ||||
_JPEG = b'\xff\xd8' | ||||
|
r4526 | |||
|
r10803 | def _pngxy(data): | ||
"""read the (width, height) from a PNG header""" | ||||
ihdr = data.index(b'IHDR') | ||||
# next 8 bytes are width/height | ||||
|
r23821 | return struct.unpack('>ii', data[ihdr+4:ihdr+12]) | ||
|
r10803 | |||
def _jpegxy(data): | ||||
"""read the (width, height) from a JPEG header""" | ||||
# adapted from http://www.64lines.com/jpeg-width-height | ||||
|
r22947 | |||
|
r10803 | idx = 4 | ||
while True: | ||||
block_size = struct.unpack('>H', data[idx:idx+2])[0] | ||||
idx = idx + block_size | ||||
if data[idx:idx+2] == b'\xFF\xC0': | ||||
# found Start of Frame | ||||
iSOF = idx | ||||
break | ||||
else: | ||||
# read another block | ||||
idx += 2 | ||||
|
r23851 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | ||
return w, h | ||||
|
r23849 | |||
|
r23821 | def _gifxy(data): | ||
"""read the (width, height) from a GIF header""" | ||||
return struct.unpack('<HH', data[6:10]) | ||||
|
r10803 | |||
|
r23849 | |||
|
r4528 | class Image(DisplayObject): | ||
_read_flags = 'rb' | ||||
|
r8077 | _FMT_JPEG = u'jpeg' | ||
_FMT_PNG = u'png' | ||||
|
r23814 | _FMT_GIF = u'gif' | ||
_ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF] | ||||
|
r23849 | _MIMETYPES = { | ||
_FMT_PNG: 'image/png', | ||||
_FMT_JPEG: 'image/jpeg', | ||||
_FMT_GIF: 'image/gif', | ||||
} | ||||
|
r4528 | |||
|
r21818 | def __init__(self, data=None, url=None, filename=None, format=None, | ||
|
r20986 | embed=None, width=None, height=None, retina=False, | ||
unconfined=False, metadata=None): | ||||
|
r23814 | """Create a PNG/JPEG/GIF image object given raw data. | ||
|
r4528 | |||
|
r12557 | When this object is returned by an input cell or passed to the | ||
|
r4528 | display function, it will result in the image being displayed | ||
in the frontend. | ||||
Parameters | ||||
---------- | ||||
data : unicode, str or bytes | ||||
|
r10619 | The raw image data or a URL or filename to load the data from. | ||
This always results in embedded image data. | ||||
|
r4528 | url : unicode | ||
|
r10619 | A URL to download the data from. If you specify `url=`, | ||
the image data will not be embedded unless you also specify `embed=True`. | ||||
|
r4528 | filename : unicode | ||
Path to a local file to load the data from. | ||||
|
r10619 | Images from a file are always embedded. | ||
|
r4528 | format : unicode | ||
|
r23814 | The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given | ||
|
r4528 | for format will be inferred from the filename extension. | ||
embed : bool | ||||
|
r6529 | Should the image data be embedded using a data URI (True) or be | ||
loaded using an <img> tag. Set this to True if you want the image | ||||
to be viewable later with no internet connection in the notebook. | ||||
Default is `True`, unless the keyword argument `url` is set, then | ||||
default value is `False`. | ||||
Note that QtConsole is not able to display images if `embed` is set to `False` | ||||
|
r8077 | width : int | ||
|
r22394 | Width in pixels to which to constrain the image in html | ||
|
r8077 | height : int | ||
|
r22394 | Height in pixels to which to constrain the image in html | ||
|
r10803 | retina : bool | ||
Automatically set the width and height to half of the measured | ||||
width and height. | ||||
This only works for embedded images because it reads the width/height | ||||
from image data. | ||||
For non-embedded images, you can just set the desired display width | ||||
and height directly. | ||||
|
r20986 | unconfined: bool | ||
Set unconfined=True to disable max-width confinement of the image. | ||||
metadata: dict | ||||
Specify extra metadata to attach to the image. | ||||
|
r6529 | |||
Examples | ||||
-------- | ||||
|
r10619 | # embedded image data, works in qtconsole and notebook | ||
# when passed positionally, the first arg can be any of raw image data, | ||||
# a URL, or a filename from which to load image data. | ||||
# The result is always embedding image data for inline images. | ||||
|
r6529 | Image('http://www.google.fr/images/srpr/logo3w.png') | ||
|
r10619 | Image('/path/to/image.jpg') | ||
Image(b'RAW_PNG_DATA...') | ||||
|
r6529 | |||
|
r10619 | # Specifying Image(url=...) does not embed the image data, | ||
# it only generates `<img>` tag with a link to the source. | ||||
# This will not work in the qtconsole or offline. | ||||
|
r6529 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | ||
|
r4528 | """ | ||
if filename is not None: | ||||
ext = self._find_ext(filename) | ||||
elif url is not None: | ||||
ext = self._find_ext(url) | ||||
|
r8077 | elif data is None: | ||
raise ValueError("No image data found. Expecting filename, url, or data.") | ||||
|
r23037 | elif isinstance(data, str) and ( | ||
|
r10050 | data.startswith('http') or _safe_exists(data) | ||
): | ||||
|
r4528 | ext = self._find_ext(data) | ||
else: | ||||
ext = None | ||||
|
r8077 | |||
|
r21818 | if format is None: | ||
if ext is not None: | ||||
if ext == u'jpg' or ext == u'jpeg': | ||||
format = self._FMT_JPEG | ||||
|
r23944 | elif ext == u'png': | ||
|
r21818 | format = self._FMT_PNG | ||
|
r23944 | elif ext == u'gif': | ||
|
r23818 | format = self._FMT_GIF | ||
|
r21818 | else: | ||
format = ext.lower() | ||||
elif isinstance(data, bytes): | ||||
# infer image type from image data header, | ||||
# only if format has not been specified. | ||||
if data[:2] == _JPEG: | ||||
format = self._FMT_JPEG | ||||
# failed to detect format, default png | ||||
if format is None: | ||||
|
r23814 | format = self._FMT_PNG | ||
|
r8077 | |||
|
r22013 | if format.lower() == 'jpg': | ||
# jpg->jpeg | ||||
format = self._FMT_JPEG | ||||
|
r23849 | |||
|
r23044 | self.format = format.lower() | ||
|
r6529 | self.embed = embed if embed is not None else (url is None) | ||
|
r8077 | |||
if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | ||||
raise ValueError("Cannot embed the '%s' image format" % (self.format)) | ||||
|
r23849 | if self.embed: | ||
self._mimetype = self._MIMETYPES.get(self.format) | ||||
|
r8077 | self.width = width | ||
self.height = height | ||||
|
r10803 | self.retina = retina | ||
|
r20986 | self.unconfined = unconfined | ||
|
r23746 | super(Image, self).__init__(data=data, url=url, filename=filename, | ||
metadata=metadata) | ||||
if self.width is None and self.metadata.get('width', {}): | ||||
self.width = metadata['width'] | ||||
if self.height is None and self.metadata.get('height', {}): | ||||
self.height = metadata['height'] | ||||
|
r22947 | |||
|
r10803 | if retina: | ||
self._retina_shape() | ||||
|
r22947 | |||
|
r23849 | |||
|
r10803 | def _retina_shape(self): | ||
"""load pixel-doubled width and height from image data""" | ||||
if not self.embed: | ||||
return | ||||
|
r23814 | if self.format == self._FMT_PNG: | ||
|
r10803 | w, h = _pngxy(self.data) | ||
|
r23814 | elif self.format == self._FMT_JPEG: | ||
|
r10803 | w, h = _jpegxy(self.data) | ||
|
r23818 | elif self.format == self._FMT_GIF: | ||
|
r23821 | w, h = _gifxy(self.data) | ||
|
r10803 | else: | ||
# retina only supports png | ||||
return | ||||
self.width = w // 2 | ||||
self.height = h // 2 | ||||
|
r4528 | |||
def reload(self): | ||||
"""Reload the raw data from file or URL.""" | ||||
if self.embed: | ||||
super(Image,self).reload() | ||||
|
r10803 | if self.retina: | ||
self._retina_shape() | ||||
|
r4528 | |||
def _repr_html_(self): | ||||
if not self.embed: | ||||
|
r20986 | width = height = klass = '' | ||
|
r8077 | if self.width: | ||
width = ' width="%d"' % self.width | ||||
if self.height: | ||||
height = ' height="%d"' % self.height | ||||
|
r20986 | if self.unconfined: | ||
klass = ' class="unconfined"' | ||||
return u'<img src="{url}"{width}{height}{klass}/>'.format( | ||||
url=self.url, | ||||
width=width, | ||||
height=height, | ||||
klass=klass, | ||||
) | ||||
|
r10490 | |||
|
r23849 | def _repr_mimebundle_(self, include=None, exclude=None): | ||
"""Return the image as a mimebundle | ||||
Any new mimetype support should be implemented here. | ||||
""" | ||||
if self.embed: | ||||
mimetype = self._mimetype | ||||
data, metadata = self._data_and_metadata(always_both=True) | ||||
if metadata: | ||||
metadata = {mimetype: metadata} | ||||
return {mimetype: data}, metadata | ||||
else: | ||||
return {'text/html': self._repr_html_()} | ||||
def _data_and_metadata(self, always_both=False): | ||||
|
r10444 | """shortcut for returning metadata with shape information, if defined""" | ||
|
r24989 | try: | ||
b64_data = b2a_base64(self.data).decode('ascii') | ||||
except TypeError: | ||||
raise FileNotFoundError( | ||||
"No such file or directory: '%s'" % (self.data)) | ||||
|
r10444 | md = {} | ||
|
r23746 | if self.metadata: | ||
md.update(self.metadata) | ||||
|
r10444 | if self.width: | ||
md['width'] = self.width | ||||
if self.height: | ||||
md['height'] = self.height | ||||
|
r20986 | if self.unconfined: | ||
md['unconfined'] = self.unconfined | ||||
|
r23849 | if md or always_both: | ||
|
r23835 | return b64_data, md | ||
|
r10444 | else: | ||
|
r23835 | return b64_data | ||
|
r4528 | |||
def _repr_png_(self): | ||||
|
r24990 | if self.embed and self.format == self._FMT_PNG: | ||
return self._data_and_metadata() | ||||
|
r4528 | |||
def _repr_jpeg_(self): | ||||
|
r24990 | if self.embed and self.format == self._FMT_JPEG: | ||
return self._data_and_metadata() | ||||
|
r4528 | |||
def _find_ext(self, s): | ||||
|
r23044 | return s.split('.')[-1].lower() | ||
|
r5080 | |||
|
r23849 | |||
|
r17001 | class Video(DisplayObject): | ||
|
r24623 | def __init__(self, data=None, url=None, filename=None, embed=False, | ||
mimetype=None, width=None, height=None): | ||||
|
r17001 | """Create a video object given raw data or an URL. | ||
When this object is returned by an input cell or passed to the | ||||
display function, it will result in the video being displayed | ||||
in the frontend. | ||||
Parameters | ||||
---------- | ||||
data : unicode, str or bytes | ||||
|
r22116 | The raw video data or a URL or filename to load the data from. | ||
Raw data will require passing `embed=True`. | ||||
|
r17001 | url : unicode | ||
|
r22116 | A URL for the video. If you specify `url=`, | ||
the image data will not be embedded. | ||||
|
r17001 | filename : unicode | ||
|
r22116 | Path to a local file containing the video. | ||
Will be interpreted as a local URL unless `embed=True`. | ||||
|
r17001 | embed : bool | ||
|
r22116 | Should the video be embedded using a data URI (True) or be | ||
loaded using a <video> tag (False). | ||||
|
r17001 | |||
|
r22116 | Since videos are large, embedding them should be avoided, if possible. | ||
You must confirm embedding as your intention by passing `embed=True`. | ||||
Local files can be displayed with URLs without embedding the content, via:: | ||||
Video('./video.mp4') | ||||
|
r17001 | |||
mimetype: unicode | ||||
|
r22116 | Specify the mimetype for embedded videos. | ||
Default will be guessed from file extension, if available. | ||||
|
r24623 | width : int | ||
Width in pixels to which to constrain the video in HTML. | ||||
If not supplied, defaults to the width of the video. | ||||
height : int | ||||
Height in pixels to which to constrain the video in html. | ||||
If not supplied, defaults to the height of the video. | ||||
|
r22115 | |||
|
r17001 | Examples | ||
-------- | ||||
|
r22115 | |||
|
r17001 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') | ||
Video('path/to/video.mp4') | ||||
|
r22116 | Video('path/to/video.mp4', embed=True) | ||
Video(b'raw-videodata', embed=True) | ||||
|
r17001 | """ | ||
|
r23037 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): | ||
|
r17001 | url = data | ||
data = None | ||||
elif os.path.exists(data): | ||||
filename = data | ||||
data = None | ||||
|
r22947 | |||
|
r22116 | if data and not embed: | ||
msg = ''.join([ | ||||
"To embed videos, you must pass embed=True ", | ||||
"(this may make your notebook files huge)\n", | ||||
"Consider passing Video(url='...')", | ||||
]) | ||||
raise ValueError(msg) | ||||
|
r17001 | |||
self.mimetype = mimetype | ||||
|
r22116 | self.embed = embed | ||
|
r24623 | self.width = width | ||
self.height = height | ||||
|
r17001 | super(Video, self).__init__(data=data, url=url, filename=filename) | ||
def _repr_html_(self): | ||||
|
r24623 | width = height = '' | ||
if self.width: | ||||
width = ' width="%d"' % self.width | ||||
if self.height: | ||||
height = ' height="%d"' % self.height | ||||
|
r17001 | # External URLs and potentially local files are not embedded into the | ||
# notebook output. | ||||
if not self.embed: | ||||
url = self.url if self.url is not None else self.filename | ||||
|
r24623 | output = """<video src="{0}" controls {1} {2}> | ||
|
r17001 | Your browser does not support the <code>video</code> element. | ||
|
r24623 | </video>""".format(url, width, height) | ||
|
r17001 | return output | ||
|
r22947 | |||
|
r22116 | # Embedded videos are base64-encoded. | ||
|
r22115 | mimetype = self.mimetype | ||
|
r17001 | if self.filename is not None: | ||
|
r22115 | if not mimetype: | ||
mimetype, _ = mimetypes.guess_type(self.filename) | ||||
|
r22947 | |||
|
r22115 | with open(self.filename, 'rb') as f: | ||
video = f.read() | ||||
else: | ||||
video = self.data | ||||
|
r23044 | if isinstance(video, str): | ||
|
r22115 | # unicode input is already b64-encoded | ||
b64_video = video | ||||
|
r17001 | else: | ||
|
r23835 | b64_video = b2a_base64(video).decode('ascii').rstrip() | ||
|
r22947 | |||
|
r24623 | output = """<video controls {0} {1}> | ||
<source src="data:{2};base64,{3}" type="{2}"> | ||||
|
r17001 | Your browser does not support the video tag. | ||
|
r24623 | </video>""".format(width, height, mimetype, b64_video) | ||
|
r17001 | return output | ||
def reload(self): | ||||
# TODO | ||||
pass | ||||
|
r5080 | |||
|
r12592 | def clear_output(wait=False): | ||
"""Clear the output of the current cell receiving output. | ||||
Parameters | ||||
---------- | ||||
wait : bool [default: false] | ||||
Wait to clear the output until new output is available to replace it.""" | ||||
|
r5080 | from IPython.core.interactiveshell import InteractiveShell | ||
|
r6422 | if InteractiveShell.initialized(): | ||
|
r12592 | InteractiveShell.instance().display_pub.clear_output(wait) | ||
|
r6422 | else: | ||
|
r22192 | print('\033[2K\r', end='') | ||
sys.stdout.flush() | ||||
print('\033[2K\r', end='') | ||||
sys.stderr.flush() | ||||
|
r15124 | |||
|
r15126 | @skip_doctest | ||
def set_matplotlib_formats(*formats, **kwargs): | ||||
"""Select figure formats for the inline backend. Optionally pass quality for JPEG. | ||||
For example, this enables PNG and JPEG output with a JPEG quality of 90%:: | ||||
In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) | ||||
To set this in your config files use the following:: | ||||
|
r22947 | |||
|
r15393 | c.InlineBackend.figure_formats = {'png', 'jpeg'} | ||
c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) | ||||
|
r15124 | |||
Parameters | ||||
|
r15126 | ---------- | ||
|
r15393 | *formats : strs | ||
One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | ||||
**kwargs : | ||||
Keyword args will be relayed to ``figure.canvas.print_figure``. | ||||
|
r15124 | """ | ||
from IPython.core.interactiveshell import InteractiveShell | ||||
from IPython.core.pylabtools import select_figure_formats | ||||
|
r15393 | # build kwargs, starting with InlineBackend config | ||
kw = {} | ||||
|
r21337 | from ipykernel.pylab.config import InlineBackend | ||
|
r15393 | cfg = InlineBackend.instance() | ||
kw.update(cfg.print_figure_kwargs) | ||||
kw.update(**kwargs) | ||||
|
r15124 | shell = InteractiveShell.instance() | ||
|
r15393 | select_figure_formats(shell, formats, **kw) | ||
|
r15124 | |||
|
r15126 | @skip_doctest | ||
|
r15395 | def set_matplotlib_close(close=True): | ||
|
r15197 | """Set whether the inline backend closes all figures automatically or not. | ||
|
r22947 | |||
|
r15126 | By default, the inline backend used in the IPython Notebook will close all | ||
matplotlib figures automatically after each cell is run. This means that | ||||
plots in different cells won't interfere. Sometimes, you may want to make | ||||
a plot in one cell and then refine it in later cells. This can be accomplished | ||||
by:: | ||||
|
r22947 | |||
|
r15126 | In [1]: set_matplotlib_close(False) | ||
|
r22947 | |||
|
r15126 | To set this in your config files use the following:: | ||
|
r22947 | |||
|
r15126 | c.InlineBackend.close_figures = False | ||
|
r22947 | |||
|
r15126 | Parameters | ||
---------- | ||||
close : bool | ||||
Should all matplotlib figures be automatically closed after each cell is | ||||
run? | ||||
""" | ||||
|
r21337 | from ipykernel.pylab.config import InlineBackend | ||
|
r15395 | cfg = InlineBackend.instance() | ||
cfg.close_figures = close | ||||