display.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. """Various display related classes.
  2. Authors : MinRK, gregcaporaso, dannystaple
  3. """
  4. from html import escape as html_escape
  5. from os.path import exists, isfile, splitext, abspath, join, isdir
  6. from os import walk, sep, fsdecode
  7. from IPython.core.display import DisplayObject, TextDisplayObject
  8. from typing import Tuple, Optional
  9. from collections.abc import Iterable
  10. __all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
  11. 'FileLink', 'FileLinks', 'Code']
  12. class Audio(DisplayObject):
  13. """Create an audio object.
  14. When this object is returned by an input cell or passed to the
  15. display function, it will result in Audio controls being displayed
  16. in the frontend (only works in the notebook).
  17. Parameters
  18. ----------
  19. data : numpy array, list, unicode, str or bytes
  20. Can be one of
  21. * Numpy 1d array containing the desired waveform (mono)
  22. * Numpy 2d array containing waveforms for each channel.
  23. Shape=(NCHAN, NSAMPLES). For the standard channel order, see
  24. http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
  25. * List of float or integer representing the waveform (mono)
  26. * String containing the filename
  27. * Bytestring containing raw PCM data or
  28. * URL pointing to a file on the web.
  29. If the array option is used, the waveform will be normalized.
  30. If a filename or url is used, the format support will be browser
  31. dependent.
  32. url : unicode
  33. A URL to download the data from.
  34. filename : unicode
  35. Path to a local file to load the data from.
  36. embed : boolean
  37. Should the audio data be embedded using a data URI (True) or should
  38. the original source be referenced. Set this to True if you want the
  39. audio to playable later with no internet connection in the notebook.
  40. Default is `True`, unless the keyword argument `url` is set, then
  41. default value is `False`.
  42. rate : integer
  43. The sampling rate of the raw data.
  44. Only required when data parameter is being used as an array
  45. autoplay : bool
  46. Set to True if the audio should immediately start playing.
  47. Default is `False`.
  48. normalize : bool
  49. Whether audio should be normalized (rescaled) to the maximum possible
  50. range. Default is `True`. When set to `False`, `data` must be between
  51. -1 and 1 (inclusive), otherwise an error is raised.
  52. Applies only when `data` is a list or array of samples; other types of
  53. audio are never normalized.
  54. Examples
  55. --------
  56. >>> import pytest
  57. >>> np = pytest.importorskip("numpy")
  58. Generate a sound
  59. >>> import numpy as np
  60. >>> framerate = 44100
  61. >>> t = np.linspace(0,5,framerate*5)
  62. >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
  63. >>> Audio(data, rate=framerate)
  64. <IPython.lib.display.Audio object>
  65. Can also do stereo or more channels
  66. >>> dataleft = np.sin(2*np.pi*220*t)
  67. >>> dataright = np.sin(2*np.pi*224*t)
  68. >>> Audio([dataleft, dataright], rate=framerate)
  69. <IPython.lib.display.Audio object>
  70. From URL:
  71. >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP
  72. >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP
  73. From a File:
  74. >>> Audio('IPython/lib/tests/test.wav') # doctest: +SKIP
  75. >>> Audio(filename='IPython/lib/tests/test.wav') # doctest: +SKIP
  76. From Bytes:
  77. >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP
  78. >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP
  79. See Also
  80. --------
  81. ipywidgets.Audio
  82. Audio widget with more more flexibility and options.
  83. """
  84. _read_flags = 'rb'
  85. def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *,
  86. element_id=None):
  87. if filename is None and url is None and data is None:
  88. raise ValueError("No audio data found. Expecting filename, url, or data.")
  89. if embed is False and url is None:
  90. raise ValueError("No url found. Expecting url when embed=False")
  91. if url is not None and embed is not True:
  92. self.embed = False
  93. else:
  94. self.embed = True
  95. self.autoplay = autoplay
  96. self.element_id = element_id
  97. super(Audio, self).__init__(data=data, url=url, filename=filename)
  98. if self.data is not None and not isinstance(self.data, bytes):
  99. if rate is None:
  100. raise ValueError("rate must be specified when data is a numpy array or list of audio samples.")
  101. self.data = Audio._make_wav(data, rate, normalize)
  102. def reload(self):
  103. """Reload the raw data from file or URL."""
  104. import mimetypes
  105. if self.embed:
  106. super(Audio, self).reload()
  107. if self.filename is not None:
  108. self.mimetype = mimetypes.guess_type(self.filename)[0]
  109. elif self.url is not None:
  110. self.mimetype = mimetypes.guess_type(self.url)[0]
  111. else:
  112. self.mimetype = "audio/wav"
  113. @staticmethod
  114. def _make_wav(data, rate, normalize):
  115. """ Transform a numpy array to a PCM bytestring """
  116. from io import BytesIO
  117. import wave
  118. try:
  119. scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize)
  120. except ImportError:
  121. scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize)
  122. fp = BytesIO()
  123. waveobj = wave.open(fp,mode='wb')
  124. waveobj.setnchannels(nchan)
  125. waveobj.setframerate(rate)
  126. waveobj.setsampwidth(2)
  127. waveobj.setcomptype('NONE','NONE')
  128. waveobj.writeframes(scaled)
  129. val = fp.getvalue()
  130. waveobj.close()
  131. return val
  132. @staticmethod
  133. def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]:
  134. import numpy as np
  135. data = np.array(data, dtype=float)
  136. if len(data.shape) == 1:
  137. nchan = 1
  138. elif len(data.shape) == 2:
  139. # In wave files,channels are interleaved. E.g.,
  140. # "L1R1L2R2..." for stereo. See
  141. # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
  142. # for channel ordering
  143. nchan = data.shape[0]
  144. data = data.T.ravel()
  145. else:
  146. raise ValueError('Array audio input must be a 1D or 2D array')
  147. max_abs_value = np.max(np.abs(data))
  148. normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
  149. scaled = data / normalization_factor * 32767
  150. return scaled.astype("<h").tobytes(), nchan
  151. @staticmethod
  152. def _validate_and_normalize_without_numpy(data, normalize):
  153. import array
  154. import sys
  155. data = array.array('f', data)
  156. try:
  157. max_abs_value = float(max([abs(x) for x in data]))
  158. except TypeError as e:
  159. raise TypeError('Only lists of mono audio are '
  160. 'supported if numpy is not installed') from e
  161. normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
  162. scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data])
  163. if sys.byteorder == 'big':
  164. scaled.byteswap()
  165. nchan = 1
  166. return scaled.tobytes(), nchan
  167. @staticmethod
  168. def _get_normalization_factor(max_abs_value, normalize):
  169. if not normalize and max_abs_value > 1:
  170. raise ValueError('Audio data must be between -1 and 1 when normalize=False.')
  171. return max_abs_value if normalize else 1
  172. def _data_and_metadata(self):
  173. """shortcut for returning metadata with url information, if defined"""
  174. md = {}
  175. if self.url:
  176. md['url'] = self.url
  177. if md:
  178. return self.data, md
  179. else:
  180. return self.data
  181. def _repr_html_(self):
  182. src = """
  183. <audio {element_id} controls="controls" {autoplay}>
  184. <source src="{src}" type="{type}" />
  185. Your browser does not support the audio element.
  186. </audio>
  187. """
  188. return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(),
  189. element_id=self.element_id_attr())
  190. def src_attr(self):
  191. import base64
  192. if self.embed and (self.data is not None):
  193. data = base64=base64.b64encode(self.data).decode('ascii')
  194. return """data:{type};base64,{base64}""".format(type=self.mimetype,
  195. base64=data)
  196. elif self.url is not None:
  197. return self.url
  198. else:
  199. return ""
  200. def autoplay_attr(self):
  201. if(self.autoplay):
  202. return 'autoplay="autoplay"'
  203. else:
  204. return ''
  205. def element_id_attr(self):
  206. if (self.element_id):
  207. return 'id="{element_id}"'.format(element_id=self.element_id)
  208. else:
  209. return ''
  210. class IFrame:
  211. """
  212. Generic class to embed an iframe in an IPython notebook
  213. """
  214. iframe = """
  215. <iframe
  216. width="{width}"
  217. height="{height}"
  218. src="{src}{params}"
  219. frameborder="0"
  220. allowfullscreen
  221. {extras}
  222. ></iframe>
  223. """
  224. def __init__(
  225. self, src, width, height, extras: Optional[Iterable[str]] = None, **kwargs
  226. ):
  227. if extras is None:
  228. extras = []
  229. self.src = src
  230. self.width = width
  231. self.height = height
  232. self.extras = extras
  233. self.params = kwargs
  234. def _repr_html_(self):
  235. """return the embed iframe"""
  236. if self.params:
  237. from urllib.parse import urlencode
  238. params = "?" + urlencode(self.params)
  239. else:
  240. params = ""
  241. return self.iframe.format(
  242. src=self.src,
  243. width=self.width,
  244. height=self.height,
  245. params=params,
  246. extras=" ".join(self.extras),
  247. )
  248. class YouTubeVideo(IFrame):
  249. """Class for embedding a YouTube Video in an IPython session, based on its video id.
  250. e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
  251. do::
  252. vid = YouTubeVideo("foo")
  253. display(vid)
  254. To start from 30 seconds::
  255. vid = YouTubeVideo("abc", start=30)
  256. display(vid)
  257. To calculate seconds from time as hours, minutes, seconds use
  258. :class:`datetime.timedelta`::
  259. start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
  260. Other parameters can be provided as documented at
  261. https://developers.google.com/youtube/player_parameters#Parameters
  262. When converting the notebook using nbconvert, a jpeg representation of the video
  263. will be inserted in the document.
  264. """
  265. def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs):
  266. self.id=id
  267. src = "https://www.youtube.com/embed/{0}".format(id)
  268. if allow_autoplay:
  269. extras = list(kwargs.get("extras", [])) + ['allow="autoplay"']
  270. kwargs.update(autoplay=1, extras=extras)
  271. super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
  272. def _repr_jpeg_(self):
  273. # Deferred import
  274. from urllib.request import urlopen
  275. try:
  276. return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
  277. except IOError:
  278. return None
  279. class VimeoVideo(IFrame):
  280. """
  281. Class for embedding a Vimeo video in an IPython session, based on its video id.
  282. """
  283. def __init__(self, id, width=400, height=300, **kwargs):
  284. src="https://player.vimeo.com/video/{0}".format(id)
  285. super(VimeoVideo, self).__init__(src, width, height, **kwargs)
  286. class ScribdDocument(IFrame):
  287. """
  288. Class for embedding a Scribd document in an IPython session
  289. Use the start_page params to specify a starting point in the document
  290. Use the view_mode params to specify display type one off scroll | slideshow | book
  291. e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
  292. ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
  293. """
  294. def __init__(self, id, width=400, height=300, **kwargs):
  295. src="https://www.scribd.com/embeds/{0}/content".format(id)
  296. super(ScribdDocument, self).__init__(src, width, height, **kwargs)
  297. class FileLink:
  298. """Class for embedding a local file link in an IPython session, based on path
  299. e.g. to embed a link that was generated in the IPython notebook as my/data.txt
  300. you would do::
  301. local_file = FileLink("my/data.txt")
  302. display(local_file)
  303. or in the HTML notebook, just::
  304. FileLink("my/data.txt")
  305. """
  306. html_link_str = "<a href='%s' target='_blank'>%s</a>"
  307. def __init__(self,
  308. path,
  309. url_prefix='',
  310. result_html_prefix='',
  311. result_html_suffix='<br>'):
  312. """
  313. Parameters
  314. ----------
  315. path : str
  316. path to the file or directory that should be formatted
  317. url_prefix : str
  318. prefix to be prepended to all files to form a working link [default:
  319. '']
  320. result_html_prefix : str
  321. text to append to beginning to link [default: '']
  322. result_html_suffix : str
  323. text to append at the end of link [default: '<br>']
  324. """
  325. if isdir(path):
  326. raise ValueError("Cannot display a directory using FileLink. "
  327. "Use FileLinks to display '%s'." % path)
  328. self.path = fsdecode(path)
  329. self.url_prefix = url_prefix
  330. self.result_html_prefix = result_html_prefix
  331. self.result_html_suffix = result_html_suffix
  332. def _format_path(self):
  333. fp = ''.join([self.url_prefix, html_escape(self.path)])
  334. return ''.join([self.result_html_prefix,
  335. self.html_link_str % \
  336. (fp, html_escape(self.path, quote=False)),
  337. self.result_html_suffix])
  338. def _repr_html_(self):
  339. """return html link to file
  340. """
  341. if not exists(self.path):
  342. return ("Path (<tt>%s</tt>) doesn't exist. "
  343. "It may still be in the process of "
  344. "being generated, or you may have the "
  345. "incorrect path." % self.path)
  346. return self._format_path()
  347. def __repr__(self):
  348. """return absolute path to file
  349. """
  350. return abspath(self.path)
  351. class FileLinks(FileLink):
  352. """Class for embedding local file links in an IPython session, based on path
  353. e.g. to embed links to files that were generated in the IPython notebook
  354. under ``my/data``, you would do::
  355. local_files = FileLinks("my/data")
  356. display(local_files)
  357. or in the HTML notebook, just::
  358. FileLinks("my/data")
  359. """
  360. def __init__(self,
  361. path,
  362. url_prefix='',
  363. included_suffixes=None,
  364. result_html_prefix='',
  365. result_html_suffix='<br>',
  366. notebook_display_formatter=None,
  367. terminal_display_formatter=None,
  368. recursive=True):
  369. """
  370. See :class:`FileLink` for the ``path``, ``url_prefix``,
  371. ``result_html_prefix`` and ``result_html_suffix`` parameters.
  372. included_suffixes : list
  373. Filename suffixes to include when formatting output [default: include
  374. all files]
  375. notebook_display_formatter : function
  376. Used to format links for display in the notebook. See discussion of
  377. formatter functions below.
  378. terminal_display_formatter : function
  379. Used to format links for display in the terminal. See discussion of
  380. formatter functions below.
  381. Formatter functions must be of the form::
  382. f(dirname, fnames, included_suffixes)
  383. dirname : str
  384. The name of a directory
  385. fnames : list
  386. The files in that directory
  387. included_suffixes : list
  388. The file suffixes that should be included in the output (passing None
  389. meansto include all suffixes in the output in the built-in formatters)
  390. recursive : boolean
  391. Whether to recurse into subdirectories. Default is True.
  392. The function should return a list of lines that will be printed in the
  393. notebook (if passing notebook_display_formatter) or the terminal (if
  394. passing terminal_display_formatter). This function is iterated over for
  395. each directory in self.path. Default formatters are in place, can be
  396. passed here to support alternative formatting.
  397. """
  398. if isfile(path):
  399. raise ValueError("Cannot display a file using FileLinks. "
  400. "Use FileLink to display '%s'." % path)
  401. self.included_suffixes = included_suffixes
  402. # remove trailing slashes for more consistent output formatting
  403. path = path.rstrip('/')
  404. self.path = path
  405. self.url_prefix = url_prefix
  406. self.result_html_prefix = result_html_prefix
  407. self.result_html_suffix = result_html_suffix
  408. self.notebook_display_formatter = \
  409. notebook_display_formatter or self._get_notebook_display_formatter()
  410. self.terminal_display_formatter = \
  411. terminal_display_formatter or self._get_terminal_display_formatter()
  412. self.recursive = recursive
  413. def _get_display_formatter(
  414. self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None
  415. ):
  416. """generate built-in formatter function
  417. this is used to define both the notebook and terminal built-in
  418. formatters as they only differ by some wrapper text for each entry
  419. dirname_output_format: string to use for formatting directory
  420. names, dirname will be substituted for a single "%s" which
  421. must appear in this string
  422. fname_output_format: string to use for formatting file names,
  423. if a single "%s" appears in the string, fname will be substituted
  424. if two "%s" appear in the string, the path to fname will be
  425. substituted for the first and fname will be substituted for the
  426. second
  427. fp_format: string to use for formatting filepaths, must contain
  428. exactly two "%s" and the dirname will be substituted for the first
  429. and fname will be substituted for the second
  430. """
  431. def f(dirname, fnames, included_suffixes=None):
  432. result = []
  433. # begin by figuring out which filenames, if any,
  434. # are going to be displayed
  435. display_fnames = []
  436. for fname in fnames:
  437. if (isfile(join(dirname,fname)) and
  438. (included_suffixes is None or
  439. splitext(fname)[1] in included_suffixes)):
  440. display_fnames.append(fname)
  441. if len(display_fnames) == 0:
  442. # if there are no filenames to display, don't print anything
  443. # (not even the directory name)
  444. pass
  445. else:
  446. # otherwise print the formatted directory name followed by
  447. # the formatted filenames
  448. dirname_output_line = dirname_output_format % dirname
  449. result.append(dirname_output_line)
  450. for fname in display_fnames:
  451. fp = fp_format % (dirname,fname)
  452. if fp_cleaner is not None:
  453. fp = fp_cleaner(fp)
  454. try:
  455. # output can include both a filepath and a filename...
  456. fname_output_line = fname_output_format % (fp, fname)
  457. except TypeError:
  458. # ... or just a single filepath
  459. fname_output_line = fname_output_format % fname
  460. result.append(fname_output_line)
  461. return result
  462. return f
  463. def _get_notebook_display_formatter(self,
  464. spacer="&nbsp;&nbsp;"):
  465. """ generate function to use for notebook formatting
  466. """
  467. dirname_output_format = \
  468. self.result_html_prefix + "%s/" + self.result_html_suffix
  469. fname_output_format = \
  470. self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
  471. fp_format = self.url_prefix + '%s/%s'
  472. if sep == "\\":
  473. # Working on a platform where the path separator is "\", so
  474. # must convert these to "/" for generating a URI
  475. def fp_cleaner(fp):
  476. # Replace all occurrences of backslash ("\") with a forward
  477. # slash ("/") - this is necessary on windows when a path is
  478. # provided as input, but we must link to a URI
  479. return fp.replace('\\','/')
  480. else:
  481. fp_cleaner = None
  482. return self._get_display_formatter(dirname_output_format,
  483. fname_output_format,
  484. fp_format,
  485. fp_cleaner)
  486. def _get_terminal_display_formatter(self,
  487. spacer=" "):
  488. """ generate function to use for terminal formatting
  489. """
  490. dirname_output_format = "%s/"
  491. fname_output_format = spacer + "%s"
  492. fp_format = '%s/%s'
  493. return self._get_display_formatter(dirname_output_format,
  494. fname_output_format,
  495. fp_format)
  496. def _format_path(self):
  497. result_lines = []
  498. if self.recursive:
  499. walked_dir = list(walk(self.path))
  500. else:
  501. walked_dir = [next(walk(self.path))]
  502. walked_dir.sort()
  503. for dirname, subdirs, fnames in walked_dir:
  504. result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
  505. return '\n'.join(result_lines)
  506. def __repr__(self):
  507. """return newline-separated absolute paths
  508. """
  509. result_lines = []
  510. if self.recursive:
  511. walked_dir = list(walk(self.path))
  512. else:
  513. walked_dir = [next(walk(self.path))]
  514. walked_dir.sort()
  515. for dirname, subdirs, fnames in walked_dir:
  516. result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
  517. return '\n'.join(result_lines)
  518. class Code(TextDisplayObject):
  519. """Display syntax-highlighted source code.
  520. This uses Pygments to highlight the code for HTML and Latex output.
  521. Parameters
  522. ----------
  523. data : str
  524. The code as a string
  525. url : str
  526. A URL to fetch the code from
  527. filename : str
  528. A local filename to load the code from
  529. language : str
  530. The short name of a Pygments lexer to use for highlighting.
  531. If not specified, it will guess the lexer based on the filename
  532. or the code. Available lexers: http://pygments.org/docs/lexers/
  533. """
  534. def __init__(self, data=None, url=None, filename=None, language=None):
  535. self.language = language
  536. super().__init__(data=data, url=url, filename=filename)
  537. def _get_lexer(self):
  538. if self.language:
  539. from pygments.lexers import get_lexer_by_name
  540. return get_lexer_by_name(self.language)
  541. elif self.filename:
  542. from pygments.lexers import get_lexer_for_filename
  543. return get_lexer_for_filename(self.filename)
  544. else:
  545. from pygments.lexers import guess_lexer
  546. return guess_lexer(self.data)
  547. def __repr__(self):
  548. return self.data
  549. def _repr_html_(self):
  550. from pygments import highlight
  551. from pygments.formatters import HtmlFormatter
  552. fmt = HtmlFormatter()
  553. style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html'))
  554. return style + highlight(self.data, self._get_lexer(), fmt)
  555. def _repr_latex_(self):
  556. from pygments import highlight
  557. from pygments.formatters import LatexFormatter
  558. return highlight(self.data, self._get_lexer(), LatexFormatter())