diff --git a/IPython/core/display.py b/IPython/core/display.py index b42e910..3aa8ee1 100644 --- a/IPython/core/display.py +++ b/IPython/core/display.py @@ -6,7 +6,11 @@ from __future__ import print_function -import base64 +try: + from base64 import encodebytes as base64_encode +except ImportError: + from base64 import encodestring as base64_encode + import json import mimetypes import os @@ -849,13 +853,17 @@ class Video(DisplayObject): Note that QtConsole is not able to display images if `embed` is set to `False` mimetype: unicode Specify the mimetype in case you load in a encoded video. + Examples -------- + Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') Video('path/to/video.mp4') Video('path/to/video.mp4', embed=False) + Video(b'videodata') + Video(u'b64-encoded-videodata') """ - if url is None and (data.startswith('http') or data.startswith('https')): + if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')): url = data data = None embed = False @@ -877,19 +885,25 @@ class Video(DisplayObject): """.format(url) return output # Embedded videos uses base64 encoded videos. + mimetype = self.mimetype if self.filename is not None: - mimetypes.init() - mimetype, encoding = mimetypes.guess_type(self.filename) - - video = open(self.filename, 'rb').read() - video_encoded = base64.b64encode(video) + if not mimetype: + mimetype, _ = mimetypes.guess_type(self.filename) + + with open(self.filename, 'rb') as f: + video = f.read() + else: + video = self.data + if isinstance(video, unicode_type): + # unicode input is already b64-encoded + b64_video = video else: - video_encoded = self.data - mimetype = self.mimetype + b64_video = base64_encode(video).decode('ascii').rstrip() + output = """""".format(mimetype, video_encoded.decode('ASCII')) + """.format(mimetype, b64_video) return output def reload(self): diff --git a/IPython/core/tests/test_display.py b/IPython/core/tests/test_display.py index 9700215..432e2e4 100644 --- a/IPython/core/tests/test_display.py +++ b/IPython/core/tests/test_display.py @@ -162,3 +162,15 @@ def test_video_embedding(): v = display.Video(f.name, embed=True) html = v._repr_html_() nt.assert_in('src="data:video/mp4;base64,YWJj"',html) + + v = display.Video(f.name, embed=True, mimetype='video/other') + html = v._repr_html_() + nt.assert_in('src="data:video/other;base64,YWJj"',html) + + v = display.Video(b'abc', embed=True, mimetype='video/mp4') + html = v._repr_html_() + nt.assert_in('src="data:video/mp4;base64,YWJj"',html) + + v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') + html = v._repr_html_() + nt.assert_in('src="data:video/xyz;base64,YWJj"',html)