Format: application/x-python-code
⬇ Download File (21.9 KB)
   1  o
   2  
   3  ��h�_�@s�dZddlmZddlmZmZmZmZm	Z	m
   4  Z
   5  ddlmZm
   6  Z
   7  mZddlmZmZddlmZmZmZgd�ZGdd	�d	e�ZGd
   8  d�de�ZGdd
   9  �d
  10  e�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)zMVarious display related classes.
  11  
  12  Authors : MinRK, gregcaporaso, dannystaple
  13  �)�escape)�exists�isfile�splitext�abspath�join�isdir)�walk�sep�fsdecode)�
  14  DisplayObject�TextDisplayObject)�Tuple�Iterable�Optional)�Audio�IFrame�YouTubeVideo�
  15  VimeoVideo�ScribdDocument�FileLink�	FileLinks�Codecs�eZdZdZdZddd��fdd�Z�fd	d
  16  �Zedd��Zed
  17  e	e
  18  effdd��Zedd��Z
  19  edd��Zdd�Zdd�Zdd�Zdd�Zdd�Z�ZS)ra�Create an audio object.
  20  
  21      When this object is returned by an input cell or passed to the
  22      display function, it will result in Audio controls being displayed
  23      in the frontend (only works in the notebook).
  24  
  25      Parameters
  26      ----------
  27      data : numpy array, list, unicode, str or bytes
  28          Can be one of
  29  
  30            * Numpy 1d array containing the desired waveform (mono)
  31            * Numpy 2d array containing waveforms for each channel.
  32              Shape=(NCHAN, NSAMPLES). For the standard channel order, see
  33              http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
  34            * List of float or integer representing the waveform (mono)
  35            * String containing the filename
  36            * Bytestring containing raw PCM data or
  37            * URL pointing to a file on the web.
  38  
  39          If the array option is used, the waveform will be normalized.
  40  
  41          If a filename or url is used, the format support will be browser
  42          dependent.
  43      url : unicode
  44          A URL to download the data from.
  45      filename : unicode
  46          Path to a local file to load the data from.
  47      embed : boolean
  48          Should the audio data be embedded using a data URI (True) or should
  49          the original source be referenced. Set this to True if you want the
  50          audio to playable later with no internet connection in the notebook.
  51  
  52          Default is `True`, unless the keyword argument `url` is set, then
  53          default value is `False`.
  54      rate : integer
  55          The sampling rate of the raw data.
  56          Only required when data parameter is being used as an array
  57      autoplay : bool
  58          Set to True if the audio should immediately start playing.
  59          Default is `False`.
  60      normalize : bool
  61          Whether audio should be normalized (rescaled) to the maximum possible
  62          range. Default is `True`. When set to `False`, `data` must be between
  63          -1 and 1 (inclusive), otherwise an error is raised.
  64          Applies only when `data` is a list or array of samples; other types of
  65          audio are never normalized.
  66  
  67      Examples
  68      --------
  69  
  70      >>> import pytest
  71      >>> np = pytest.importorskip("numpy")
  72  
  73      Generate a sound
  74  
  75      >>> import numpy as np
  76      >>> framerate = 44100
  77      >>> t = np.linspace(0,5,framerate*5)
  78      >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
  79      >>> Audio(data, rate=framerate)
  80      <IPython.lib.display.Audio object>
  81  
  82      Can also do stereo or more channels
  83  
  84      >>> dataleft = np.sin(2*np.pi*220*t)
  85      >>> dataright = np.sin(2*np.pi*224*t)
  86      >>> Audio([dataleft, dataright], rate=framerate)
  87      <IPython.lib.display.Audio object>
  88  
  89      From URL:
  90  
  91      >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav")  # doctest: +SKIP
  92      >>> Audio(url="http://www.w3schools.com/html/horse.ogg")  # doctest: +SKIP
  93  
  94      From a File:
  95  
  96      >>> Audio('IPython/lib/tests/test.wav')  # doctest: +SKIP
  97      >>> Audio(filename='IPython/lib/tests/test.wav')  # doctest: +SKIP
  98  
  99      From Bytes:
 100  
 101      >>> Audio(b'RAW_WAV_DATA..')  # doctest: +SKIP
 102      >>> Audio(data=b'RAW_WAV_DATA..')  # doctest: +SKIP
 103  
 104      See Also
 105      --------
 106      ipywidgets.Audio
 107  
 108           Audio widget with more more flexibility and options.
 109  
 110      �rbNFT��
 111  element_idc	s�|dur|dur|durtd��|dur|durtd��|dur(|dur(d|_nd|_||_||_tt|�j|||d�|jdurYt|jt	�s[|durOtd��t�
 112  |||�|_dSdSdS)Nz6No audio data found. Expecting filename, url, or data.Fz,No url found. Expecting url when embed=FalseT��data�url�filenamezKrate must be specified when data is a numpy array or list of audio samples.)�
 113  ValueError�embed�autoplayr�superr�__init__r�
 114  isinstance�bytes�	_make_wav)	�selfrrrr!�rater"�	normalizer��	__class__��Ic:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/lib/display.pyr$ps�zAudio.__init__csfddl}|jrtt|���|jdur|�|j�d|_dS|jdur.|�|j�d|_dSd|_dS)z%Reload the raw data from file or URL.rNz	audio/wav)	�	mimetypesr!r#r�reloadr�
 115  guess_type�mimetyper)r(r/r+r-r.r0�s
 116  
 117  
 118  zAudio.reloadc
 119  Cs�ddlm}ddl}z
 120  t�||�\}}Wnty%t�||�\}}Ynw|�}|j|dd�}|�|�|�	|�|�
 121  d�|�dd�|�|�|�
 122  �}	|��|	S)z- Transform a numpy array to a PCM bytestring r)�BytesION�wb)�mode��NONE)�ior3�waver�"_validate_and_normalize_with_numpy�ImportError�%_validate_and_normalize_without_numpy�openZsetnchannelsZsetframerateZsetsampwidthZsetcomptypeZwriteframes�getvalue�close)
 123  rr)r*r3r9�scaled�nchan�fpZwaveobj�valr-r-r.r'�s"�
 124  
 125  
 126  
 127  zAudio._make_wav�returncCs�ddl}|j|td�}t|j�dkrd}nt|j�dkr'|jd}|j��}ntd��|�|�	|��}t
 128  �||�}||d}|�d��
 129  �|fS)Nr)Zdtype�r6z*Array audio input must be a 1D or 2D array��z<h)�numpy�array�float�len�shape�TZravelr �max�absr�_get_normalization_factorZastype�tobytes)rr*�nprA�
 130  max_abs_value�normalization_factorr@r-r-r.r:�s
 131  z(Audio._validate_and_normalize_with_numpyc
 132  s�ddl}ddl}|�d|�}z
 133  ttdd�|D���}Wnty,}ztd�|�d}~wwt�||��|�d�fdd�|D��}|jdkrI|��d	}|�	�|fS)
 134  Nr�fcSsg|]}t|��qSr-)rN��.0�xr-r-r.�
 135  <listcomp>�sz?Audio._validate_and_normalize_without_numpy.<locals>.<listcomp>z@Only lists of mono audio are supported if numpy is not installed�hcsg|]
 136  }t|�d��qS)rF)�intrU�rSr-r.rX�s�bigrE)
 137  rH�sysrIrM�	TypeErrorrrO�	byteorder�byteswaprP)rr*rHr]rR�er@rAr-r[r.r<�s"���
 138  z+Audio._validate_and_normalize_without_numpycCs |s
 139  |dkr
 140  td��|r|SdS)NrEz9Audio data must be between -1 and 1 when normalize=False.)r )rRr*r-r-r.rO�szAudio._get_normalization_factorcCs(i}|jr
 141  |j|d<|r|j|fS|jS)z@shortcut for returning metadata with url information, if definedr)rr)r(�mdr-r-r.�_data_and_metadata�s
 142  
 143  zAudio._data_and_metadatacCs$d}|j|��|j|��|��d�S)Nz�
 144                  <audio {element_id} controls="controls" {autoplay}>
 145                      <source src="{src}" type="{type}" />
 146                      Your browser does not support the audio element.
 147                  </audio>
 148                )�src�typer"r)�format�src_attrr2�
 149  autoplay_attr�element_id_attr)r(rdr-r-r.�_repr_html_�s�zAudio._repr_html_cCsRddl}|jr|jdur|�|j��d�}}dj|j|d�S|jdur'|jSdS)Nr�asciizdata:{type};base64,{base64})re�base64�)rlr!r�	b64encode�decoderfr2r)r(rlrr-r-r.rg�s�
 150  zAudio.src_attrcCs|jrdSdS)Nzautoplay="autoplay"rm)r"�r(r-r-r.rh�szAudio.autoplay_attrcCs|jr
 151  dj|jd�SdS)Nzid="{element_id}"rrm)rrfrpr-r-r.ri�szAudio.element_id_attr)NNNNNFT)�__name__�
 152  __module__�__qualname__�__doc__Z_read_flagsr$r0�staticmethodr'rr&rZr:r<rOrcrjrgrhri�
 153  __classcell__r-r-r+r.rs(\�
 154  
 155  
 156  
 157  
 158  rc@s6eZdZdZdZ	d	deeefdd�Zdd�Z	dS)
 159  rzA
 160      Generic class to embed an iframe in an IPython notebook
 161      z�
 162          <iframe
 163              width="{width}"
 164              height="{height}"
 165              src="{src}{params}"
 166              frameborder="0"
 167              allowfullscreen
 168              {extras}
 169          ></iframe>
 170          N�extrascKs.|durg}||_||_||_||_||_dS�N)rd�width�heightrw�params)r(rdryrzrw�kwargsr-r-r.r$s
 171  zIFrame.__init__cCsJ|jrddlm}d||j�}nd}|jj|j|j|j|d�|j	�d�S)zreturn the embed iframer)�	urlencode�?rm� )rdryrzr{rw)
 172  r{�urllib.parser}�iframerfrdryrzrrw)r(r}r{r-r-r.rjs
 173  �zIFrame._repr_html_rx)
 174  rqrrrsrtr�rr�strr$rjr-r-r-r.rs�
 175  
 176  �rcs*eZdZdZd	�fdd�	Zdd�Z�ZS)
 177  ra�Class for embedding a YouTube Video in an IPython session, based on its video id.
 178  
 179      e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
 180      do::
 181  
 182          vid = YouTubeVideo("foo")
 183          display(vid)
 184  
 185      To start from 30 seconds::
 186  
 187          vid = YouTubeVideo("abc", start=30)
 188          display(vid)
 189  
 190      To calculate seconds from time as hours, minutes, seconds use
 191      :class:`datetime.timedelta`::
 192  
 193          start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
 194  
 195      Other parameters can be provided as documented at
 196      https://developers.google.com/youtube/player_parameters#Parameters
 197      
 198      When converting the notebook using nbconvert, a jpeg representation of the video
 199      will be inserted in the document.
 200      ��,FcsX||_d�|�}|rt|�dg��dg}|jd|d�tt|�j|||fi|��dS)Nz!https://www.youtube.com/embed/{0}rwzallow="autoplay"rE)r"rw)�idrf�list�get�updater#rr$)r(r�ryrzZallow_autoplayr|rdrwr+r-r.r$Is
 201   zYouTubeVideo.__init__cCs:ddlm}z|dj|jd����WStyYdSw)Nr)�urlopenz-https://img.youtube.com/vi/{id}/hqdefault.jpg)r�)�urllib.requestr�rfr��read�IOError)r(r�r-r-r.�_repr_jpeg_Qs�zYouTubeVideo._repr_jpeg_)r�r�F)rqrrrsrtr$r�rvr-r-r+r.r/src�"eZdZdZd�fdd�	Z�ZS)rzY
 202      Class for embedding a Vimeo video in an IPython session, based on its video id.
 203      r�r�c�*d�|�}tt|�j|||fi|��dS)Nz"https://player.vimeo.com/video/{0})rfr#rr$�r(r�ryrzr|rdr+r-r.r$_�
 204   zVimeoVideo.__init__�r�r��rqrrrsrtr$rvr-r-r+r.rZsrcr�)ra�
 205      Class for embedding a Scribd document in an IPython session
 206  
 207      Use the start_page params to specify a starting point in the document
 208      Use the view_mode params to specify display type one off scroll | slideshow | book
 209  
 210      e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
 211  
 212      ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
 213      r�r�cr�)Nz)https://www.scribd.com/embeds/{0}/content)rfr#rr$r�r+r-r.r$or�zScribdDocument.__init__r�r�r-r-r+r.rcsrc@s<eZdZdZdZ			ddd�Zdd�Zd	d
 214  �Zdd�Zd
 215  S)raGClass for embedding a local file link in an IPython session, based on path
 216  
 217      e.g. to embed a link that was generated in the IPython notebook as my/data.txt
 218  
 219      you would do::
 220  
 221          local_file = FileLink("my/data.txt")
 222          display(local_file)
 223  
 224      or in the HTML notebook, just::
 225  
 226          FileLink("my/data.txt")
 227      z#<a href='%s' target='_blank'>%s</a>rm�<br>cCs4t|�r
 228  td|��t|�|_||_||_||_dS)a�
 229          Parameters
 230          ----------
 231          path : str
 232              path to the file or directory that should be formatted
 233          url_prefix : str
 234              prefix to be prepended to all files to form a working link [default:
 235              '']
 236          result_html_prefix : str
 237              text to append to beginning to link [default: '']
 238          result_html_suffix : str
 239              text to append at the end of link [default: '<br>']
 240          zICannot display a directory using FileLink. Use FileLinks to display '%s'.N)rr r�path�
 241  url_prefix�result_html_prefix�result_html_suffix)r(r�r�r�r�r-r-r.r$�s�
 242  
 243  zFileLink.__init__c	Cs>d�|jt|j�g�}d�|j|j|t|jdd�f|jg�S)NrmF)�quote)rr��html_escaper�r��
 244  html_link_strr�)r(rBr-r-r.�_format_path�s��zFileLink._format_pathcCst|j�s
 245  d|jS|��S)z!return html link to file
 246          zxPath (<tt>%s</tt>) doesn't exist. It may still be in the process of being generated, or you may have the incorrect path.)rr�r�rpr-r-r.rj�s
 247  
 248  �zFileLink._repr_html_cCs
 249  t|j�S)z%return absolute path to file
 250          )rr�rpr-r-r.�__repr__�s
 251  zFileLink.__repr__N)rmrmr�)	rqrrrsrtr�r$r�rjr�r-r-r-r.rss
 252  �rc@s\eZdZdZ							ddd�Z	ddd	�Z	
 253  ddd�Z	
 254  ddd�Zdd�Zdd�Z	dS)raNClass for embedding local file links in an IPython session, based on path
 255  
 256      e.g. to embed links to files that were generated in the IPython notebook
 257      under ``my/data``, you would do::
 258  
 259          local_files = FileLinks("my/data")
 260          display(local_files)
 261  
 262      or in the HTML notebook, just::
 263  
 264          FileLinks("my/data")
 265      rmNr�Tc		Csbt|�r
 266  td|��||_|�d�}||_||_||_||_|p#|��|_	|p*|�
 267  �|_||_dS)a�
 268          See :class:`FileLink` for the ``path``, ``url_prefix``,
 269          ``result_html_prefix`` and ``result_html_suffix`` parameters.
 270  
 271          included_suffixes : list
 272            Filename suffixes to include when formatting output [default: include
 273            all files]
 274  
 275          notebook_display_formatter : function
 276            Used to format links for display in the notebook. See discussion of
 277            formatter functions below.
 278  
 279          terminal_display_formatter : function
 280            Used to format links for display in the terminal. See discussion of
 281            formatter functions below.
 282  
 283          Formatter functions must be of the form::
 284  
 285              f(dirname, fnames, included_suffixes)
 286  
 287          dirname : str
 288            The name of a directory
 289          fnames : list
 290            The files in that directory
 291          included_suffixes : list
 292            The file suffixes that should be included in the output (passing None
 293            meansto include all suffixes in the output in the built-in formatters)
 294          recursive : boolean
 295            Whether to recurse into subdirectories. Default is True.
 296  
 297          The function should return a list of lines that will be printed in the
 298          notebook (if passing notebook_display_formatter) or the terminal (if
 299          passing terminal_display_formatter). This function is iterated over for
 300          each directory in self.path. Default formatters are in place, can be
 301          passed here to support alternative formatting.
 302  
 303          zDCannot display a file using FileLinks. Use FileLink to display '%s'.�/N)
 304  rr �included_suffixes�rstripr�r�r�r��_get_notebook_display_formatter�notebook_display_formatter�_get_terminal_display_formatter�terminal_display_formatter�	recursive)	r(r�r�r�r�r�r�r�r�r-r-r.r$�s.�
 305  
 306  �
 307  �
 308  zFileLinks.__init__csd����fdd�	}|S)akgenerate built-in formatter function
 309  
 310          this is used to define both the notebook and terminal built-in
 311           formatters as they only differ by some wrapper text for each entry
 312  
 313          dirname_output_format: string to use for formatting directory
 314           names, dirname will be substituted for a single "%s" which
 315           must appear in this string
 316          fname_output_format: string to use for formatting file names,
 317           if a single "%s" appears in the string, fname will be substituted
 318           if two "%s" appear in the string, the path to fname will be
 319            substituted for the first and fname will be substituted for the
 320            second
 321          fp_format: string to use for formatting filepaths, must contain
 322           exactly two "%s" and the dirname will be substituted for the first
 323           and fname will be substituted for the second
 324          Nc		s�g}g}|D]}tt||��r |dust|�d|vr |�|�qt|�dkr*	|S�|}|�|�|D]+}�||f}�durE�|�}z�||f}Wn
 325  tyZ�|}Ynw|�|�q5|S)NrEr)rrr�appendrJr^)	�dirname�fnamesr��resultZdisplay_fnames�fnameZdirname_output_linerBZfname_output_line��dirname_output_format�fname_output_format�
 326  fp_cleaner�	fp_formatr-r.rTs0
 327  ��
 328  �z+FileLinks._get_display_formatter.<locals>.frxr-)r(r�r�r�r�rTr-r�r.�_get_display_formatters z FileLinks._get_display_formatter�&nbsp;&nbsp;cCsV|jd|j}|j||j|j}|jd}tdkr!dd�}nd}|�||||�S)z: generate function to use for notebook formatting
 329          �%s/�%s/%s�\cSs|�dd�S)Nr�r�)�replace)rBr-r-r.r�Esz=FileLinks._get_notebook_display_formatter.<locals>.fp_cleanerN)r�r�r�r�r
 330  r�)r(�spacerr�r�r�r�r-r-r.r�9s��
 331  
 332  �z)FileLinks._get_notebook_display_formatter�  cCsd}|d}d}|�|||�S)z: generate function to use for terminal formatting
 333          r�z%sr�)r�)r(r�r�r�r�r-r-r.r�Rs�z)FileLinks._get_terminal_display_formattercC�`g}|jr
 334  tt|j��}ntt|j��g}|��|D]\}}}||�|||j�7}qd�|�S)N�
 335  )	r�r�r	r��next�sortr�r�r�r(Zresult_linesZ
 336  walked_dirr��subdirsr�r-r-r.r�^s
 337  zFileLinks._format_pathcCr�)z0return newline-separated absolute paths
 338          r�)	r�r�r	r�r�r�r�r�rr�r-r-r.r�is
 339  zFileLinks.__repr__)rmNrmr�NNTrx)r�)r�)
 340  rqrrrsrtr$r�r�r�r�r�r-r-r-r.r�s$
 341  �B
 342  �7
 343  �
 344  �rcsBeZdZdZd
 345  �fdd�	Zdd�Zdd�Zd	d
 346  �Zdd�Z�Z	S)raDisplay syntax-highlighted source code.
 347  
 348      This uses Pygments to highlight the code for HTML and Latex output.
 349  
 350      Parameters
 351      ----------
 352      data : str
 353          The code as a string
 354      url : str
 355          A URL to fetch the code from
 356      filename : str
 357          A local filename to load the code from
 358      language : str
 359          The short name of a Pygments lexer to use for highlighting.
 360          If not specified, it will guess the lexer based on the filename
 361          or the code. Available lexers: http://pygments.org/docs/lexers/
 362      Ncs||_t�j|||d�dS)Nr)�languager#r$)r(rrrr�r+r-r.r$�sz
 363  Code.__init__cCsN|jrddlm}||j�S|jrddlm}||j�Sddlm}||j�S)Nr)�get_lexer_by_name)�get_lexer_for_filename)�guess_lexer)r�Zpygments.lexersr�rr�r�r)r(r�r�r�r-r-r.�
 364  _get_lexer�s
 365  
 366  
 367  zCode._get_lexercCs|jSrx)rrpr-r-r.r��sz
 368  Code.__repr__cCsDddlm}ddlm}|�}d�|�d��}|||j|��|�S)Nr��	highlight)�
 369  HtmlFormatterz<style>{}</style>z.output_html)�pygmentsr��pygments.formattersr�rfZget_style_defsrr�)r(r�r��fmt�styler-r-r.rj�s
 370  zCode._repr_html_cCs,ddlm}ddlm}||j|��|��S)Nrr�)�LatexFormatter)r�r�r�r�rr�)r(r�r�r-r-r.�_repr_latex_�szCode._repr_latex_)NNNN)
 371  rqrrrsrtr$r�r�rjr�rvr-r-r+r.rwsrN) rt�htmlrr�Zos.pathrrrrrr�osr	r
 372  rZIPython.core.displayrr
 373  �typingrrr�__all__r�objectrrrrrrrr-r-r-r.�<module>s" s,+	BC