display.py 24 KB

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