
    <h_                         S r SSKJr  SSKJrJrJrJrJ	r	J
r
  SSKJrJrJr  SSKJrJr  SSKJrJrJr  / SQr " S S	\5      r " S
 S5      r " S S\5      r " S S\5      r " S S\5      r " S S5      r " S S\5      r " S S\5      rg)zMVarious display related classes.

Authors : MinRK, gregcaporaso, dannystaple
    )escape)existsisfilesplitextabspathjoinisdir)walksepfsdecode)DisplayObjectTextDisplayObject)TupleIterableOptional)AudioIFrameYouTubeVideo
VimeoVideoScribdDocumentFileLink	FileLinksCodec                      ^  \ rS rSrSrSrSSS.U 4S jjjrU 4S jr\S 5       r	\S	\
\\4   4S
 j5       r\S 5       r\S 5       rS rS rS rS rS rSrU =r$ )r      am  Create an audio object.

When this object is returned by an input cell or passed to the
display function, it will result in Audio controls being displayed
in the frontend (only works in the notebook).

Parameters
----------
data : numpy array, list, unicode, str or bytes
    Can be one of

      * Numpy 1d array containing the desired waveform (mono)
      * Numpy 2d array containing waveforms for each channel.
        Shape=(NCHAN, NSAMPLES). For the standard channel order, see
        http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
      * List of float or integer representing the waveform (mono)
      * String containing the filename
      * Bytestring containing raw PCM data or
      * URL pointing to a file on the web.

    If the array option is used, the waveform will be normalized.

    If a filename or url is used, the format support will be browser
    dependent.
url : unicode
    A URL to download the data from.
filename : unicode
    Path to a local file to load the data from.
embed : boolean
    Should the audio data be embedded using a data URI (True) or should
    the original source be referenced. Set this to True if you want the
    audio to playable later with no internet connection in the notebook.

    Default is `True`, unless the keyword argument `url` is set, then
    default value is `False`.
rate : integer
    The sampling rate of the raw data.
    Only required when data parameter is being used as an array
autoplay : bool
    Set to True if the audio should immediately start playing.
    Default is `False`.
normalize : bool
    Whether audio should be normalized (rescaled) to the maximum possible
    range. Default is `True`. When set to `False`, `data` must be between
    -1 and 1 (inclusive), otherwise an error is raised.
    Applies only when `data` is a list or array of samples; other types of
    audio are never normalized.

Examples
--------

>>> import pytest
>>> np = pytest.importorskip("numpy")

Generate a sound

>>> import numpy as np
>>> framerate = 44100
>>> t = np.linspace(0,5,framerate*5)
>>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
>>> Audio(data, rate=framerate)
<IPython.lib.display.Audio object>

Can also do stereo or more channels

>>> dataleft = np.sin(2*np.pi*220*t)
>>> dataright = np.sin(2*np.pi*224*t)
>>> Audio([dataleft, dataright], rate=framerate)
<IPython.lib.display.Audio object>

From URL:

>>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav")  # doctest: +SKIP
>>> Audio(url="http://www.w3schools.com/html/horse.ogg")  # doctest: +SKIP

From a File:

>>> Audio('IPython/lib/tests/test.wav')  # doctest: +SKIP
>>> Audio(filename='IPython/lib/tests/test.wav')  # doctest: +SKIP

From Bytes:

>>> Audio(b'RAW_WAV_DATA..')  # doctest: +SKIP
>>> Audio(data=b'RAW_WAV_DATA..')  # doctest: +SKIP

See Also
--------
ipywidgets.Audio

     Audio widget with more more flexibility and options.

rbN
element_idc                l  > Uc  Uc  Uc  [        S5      eUSL a  Uc  [        S5      eUb  USLa  SU l        OSU l        X`l        Xl        [        [
        U ]  XUS9  U R                  bJ  [        U R                  [        5      (       d*  Uc  [        S5      e[
        R                  XU5      U l        g g g )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.)
ValueErrorembedautoplayr   superr   __init__r!   
isinstancebytes	_make_wav)
selfr!   r#   r"   r%   rater&   	normalizer   	__class__s
            fC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\IPython/lib/display.pyr(   Audio.__init__p   s    UVVE>ckKLL?uD0DJDJ $eT##J99 DIIu)E)E| !nooI>DI *F     c                 &  > SSK nU R                  (       a  [        [        U ]  5         U R
                  b$  UR                  U R
                  5      S   U l        gU R                  b$  UR                  U R                  5      S   U l        gSU l        g)z%Reload the raw data from file or URL.r   Nz	audio/wav)		mimetypesr%   r'   r   reloadr#   
guess_typemimetyper"   )r,   r4   r/   s     r0   r5   Audio.reload   sk    ::%%'==$%00?BDMXX!%00:1=DM'DMr2   c                    SSK Jn  SSKn [        R	                  X5      u  pVU" 5       nUR                  USS9nUR                  U5        UR                  U5        UR                  S5        UR                  SS5        UR                  U5        UR                  5       n	UR                  5         U	$ ! [
         a    [        R                  X5      u  pV Nf = f)z,Transform a numpy array to a PCM bytestring r   )BytesIONwb)mode   NONE)ior:   waver   "_validate_and_normalize_with_numpyImportError%_validate_and_normalize_without_numpyopensetnchannelssetframeratesetsampwidthsetcomptypewriteframesgetvalueclose)
r!   r-   r.   r:   r@   scalednchanfpwaveobjvals
             r0   r+   Audio._make_wav   s     		Y!DDTUMF Y))BD))U#T"QF6*F#kkm
  	Y!GGXMFE	Ys   B2 2!CCreturnc                    SS K nUR                  U [        S9n [        U R                  5      S:X  a  SnON[        U R                  5      S:X  a*  U R                  S   nU R
                  R                  5       n O[        S5      eUR                  UR                  U 5      5      n[        R                  XA5      nX-  S-  nUR                  S5      R                  5       U4$ )Nr   )dtype   r=   z*Array audio input must be a 1D or 2D array  z<h)numpyarrayfloatlenshapeTravelr$   maxabsr   _get_normalization_factorastypetobytes)r!   r.   nprM   max_abs_valuenormalization_factorrL   s          r0   rA   (Audio._validate_and_normalize_with_numpy   s    xxEx*tzz?aE_!
 JJqME66<<>DIJJrvvd|,$>>}X,u4}}T"**,e33r2   c           
         SS K nSS KnUR                  SU 5      n  [        [        U  Vs/ s H  n[	        U5      PM     sn5      5      n[        R                  XQ5      nUR                  SU  Vs/ s H  n[        XG-  S-  5      PM     sn5      nUR                  S:X  a  UR                  5         Sn	UR                  5       U	4$ s  snf ! [
         a  n[        S5      UeS nAff = fs  snf )Nr   fz@Only lists of mono audio are supported if numpy is not installedhrV   bigrU   )rX   sysrY   r^   r_   	TypeErrorr   r`   int	byteorderbyteswaprb   )
r!   r.   rX   rk   xrd   ere   rL   rM   s
             r0   rC   +Audio._validate_and_normalize_without_numpy   s    {{3%	>!#t&<t!s1vt&<"=>M
  %>>}XSRV"WRVQ3q'?%'G#HRV"WX==E!OO~~&& '= 	> 6 7<=>	>
 #Xs-   C	 CC	 /C'
C	 	
C$CC$c                 H    U(       d  U S:  a  [        S5      eU(       a  U $ S$ )NrU   z9Audio data must be between -1 and 1 when normalize=False.)r$   )rd   r.   s     r0   r`   Audio._get_normalization_factor   s%    ]Q.XYY )}0q0r2   c                     0 nU R                   (       a  U R                   US'   U(       a  U R                  U4$ U R                  $ )z@shortcut for returning metadata with url information, if definedr"   )r"   r!   )r,   mds     r0   _data_and_metadataAudio._data_and_metadata   s6    88BuI99b= 99r2   c                     SnUR                  U R                  5       U R                  U R                  5       U R	                  5       S9$ )Nz
                <audio {element_id} controls="controls" {autoplay}>
                    <source src="{src}" type="{type}" />
                    Your browser does not support the audio element.
                </audio>
              )srctyper&   r   )formatsrc_attrr7   autoplay_attrelement_id_attr)r,   rz   s     r0   _repr_html_Audio._repr_html_   sF     zzdmmoDMMDL^L^L`%)%9%9%;  = 	=r2   c                    SS K nU R                  (       aR  U R                  bE  UR                  U R                  5      R	                  S5      =p!SR                  U R                  US9$ U R                  b  U R                  $ g)Nr   asciizdata:{type};base64,{base64})r{   base64 )r   r%   r!   	b64encodedecoder|   r7   r"   )r,   r   r!   s      r0   r}   Audio.src_attr   sp    ::4990 **4995<<WEED4;;CG < I IXX!88Or2   c                 (    U R                   (       a  gg)Nzautoplay="autoplay"r   )r&   r,   s    r0   r~   Audio.autoplay_attr   s    ==(r2   c                 X    U R                   (       a  SR                  U R                   S9$ g)Nzid="{element_id}"r   r   )r   r|   r   s    r0   r   Audio.element_id_attr   s$    OO&---IIr2   )r&   r!   r   r%   r7   )NNNNNFT)__name__
__module____qualname____firstlineno____doc___read_flagsr(   r5   staticmethodr+   r   r*   rm   rA   rC   r`   rw   r   r}   r~   r   __static_attributes____classcell__r/   s   @r0   r   r      s    [x K? ? ?((  , 4uUCZ?P 4 4* ' '& 1 1
=	 r2   r   c                   B    \ rS rSrSrSr S	S\\\      4S jjr	S r
Srg)
r   i  z9
Generic class to embed an iframe in an IPython notebook
z
        <iframe
            width="{width}"
            height="{height}"
            src="{src}{params}"
            frameborder="0"
            allowfullscreen
            {extras}
        ></iframe>
        Nextrasc                 J    Uc  / nXl         X l        X0l        X@l        XPl        g N)rz   widthheightr   params)r,   rz   r   r   r   kwargss         r0   r(   IFrame.__init__  s'     >F
r2   c           	         U R                   (       a  SSKJn  SU" U R                   5      -   nOSnU R                  R	                  U R
                  U R                  U R                  USR                  U R                  5      S9$ )zreturn the embed iframer   )	urlencode?r    )rz   r   r   r   r   )
r   urllib.parser   iframer|   rz   r   r   r   r   )r,   r   r   s      r0   r   IFrame._repr_html_  sh    ;;.9T[[11FF{{!!**;;88DKK( " 
 	
r2   )r   r   r   rz   r   r   )r   r   r   r   r   r   r   r   strr(   r   r    r2   r0   r   r     s0    	F EI
*28C=*A

r2   r   c                   6   ^  \ rS rSrSrSU 4S jjrS rSrU =r$ )r   i/  a  Class for embedding a YouTube Video in an IPython session, based on its video id.

e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
do::

    vid = YouTubeVideo("foo")
    display(vid)

To start from 30 seconds::

    vid = YouTubeVideo("abc", start=30)
    display(vid)

To calculate seconds from time as hours, minutes, seconds use
:class:`datetime.timedelta`::

    start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())

Other parameters can be provided as documented at
https://developers.google.com/youtube/player_parameters#Parameters

When converting the notebook using nbconvert, a jpeg representation of the video
will be inserted in the document.
c                    > Xl         SR                  U5      nU(       a/  [        UR                  S/ 5      5      S/-   nUR	                  SUS9  [
        [        U ]  " XbU40 UD6  g )Nz!https://www.youtube.com/embed/{0}r   zallow="autoplay"rU   )r&   r   )idr|   listgetupdater'   r   r(   )	r,   r   r   r   allow_autoplayr   rz   r   r/   s	           r0   r(   YouTubeVideo.__init__I  s_    188<&**Xr237I6JJFMM1VM4lD*3vHHr2   c                     SSK Jn   U" SR                  U R                  S95      R	                  5       $ ! [
         a     g f = f)Nr   )urlopenz-https://img.youtube.com/vi/{id}/hqdefault.jpgr   )urllib.requestr   r|   r   readIOError)r,   r   s     r0   _repr_jpeg_YouTubeVideo._repr_jpeg_Q  sF    *	JQQUYU\U\Q]^ccee 		s   ,5 
AAr   )  ,  F)	r   r   r   r   r   r(   r   r   r   r   s   @r0   r   r   /  s    2I r2   r   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )r   iZ  zQ
Class for embedding a Vimeo video in an IPython session, based on its video id.
c                 T   > SR                  U5      n[        [        U ]  " XRU40 UD6  g )Nz"https://player.vimeo.com/video/{0})r|   r'   r   r(   r,   r   r   r   r   rz   r/   s         r0   r(   VimeoVideo.__init___  s)    077;j$(VFvFr2   r   r   r   r   r   r   r   r   r(   r   r   r   s   @r0   r   r   Z  s    G Gr2   r   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )r   ic  av  
Class for embedding a Scribd document in an IPython session

Use the start_page params to specify a starting point in the document
Use the view_mode params to specify display type one off scroll | slideshow | book

e.g to Display Wes' foundational paper about PANDAS in book mode from page 3

ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
c                 T   > SR                  U5      n[        [        U ]  " XRU40 UD6  g )Nz)https://www.scribd.com/embeds/{0}/content)r|   r'   r   r(   r   s         r0   r(   ScribdDocument.__init__o  s)    7>>rBnd,SJ6Jr2   r   r   r   r   s   @r0   r   r   c  s    	K Kr2   r   c                   >    \ rS rSrSrSr   S
S jrS rS rS r	Sr
g	)r   is  a+  Class for embedding a local file link in an IPython session, based on path

e.g. to embed a link that was generated in the IPython notebook as my/data.txt

you would do::

    local_file = FileLink("my/data.txt")
    display(local_file)

or in the HTML notebook, just::

    FileLink("my/data.txt")
z#<a href='%s' target='_blank'>%s</a>c                     [        U5      (       a  [        SU-  5      e[        U5      U l        X l        X0l        X@l        g)a_  
Parameters
----------
path : str
    path to the file or directory that should be formatted
url_prefix : str
    prefix to be prepended to all files to form a working link [default:
    '']
result_html_prefix : str
    text to append to beginning to link [default: '']
result_html_suffix : str
    text to append at the end of link [default: '<br>']
zICannot display a directory using FileLink. Use FileLinks to display '%s'.N)r	   r$   r   path
url_prefixresult_html_prefixresult_html_suffix)r,   r   r   r   r   s        r0   r(   FileLink.__init__  sC    $ ;; /156 7 7TN	$"4"4r2   c           
          SR                  U R                  [        U R                  5      /5      nSR                  U R                  U R
                  U[        U R                  SS94-  U R                  /5      $ )Nr   F)quote)r   r   html_escaper   r   html_link_strr   )r,   rN   s     r0   _format_pathFileLink._format_path  sk    WWdoo{499'=>?ww//**TYYe!DEF//1 2 	2r2   c                 t    [        U R                  5      (       d  SU R                  -  $ U R                  5       $ )z!return html link to file
        zxPath (<tt>%s</tt>) doesn't exist. It may still be in the process of being generated, or you may have the incorrect path.)r   r   r   r   s    r0   r   FileLink._repr_html_  s<     dii  & )-		2 3
   ""r2   c                 ,    [        U R                  5      $ )z%return absolute path to file
        )r   r   r   s    r0   __repr__FileLink.__repr__  s     tyy!!r2   )r   r   r   r   N)r   r   <br>)r   r   r   r   r   r   r(   r   r   r   r   r   r2   r0   r   r   s  s-     :M $&$*	542	#"r2   r   c                   `    \ rS rSrSr       SS jr SS jr SS jr SS jrS r	S	 r
S
rg)r   i  a2  Class for embedding local file links in an IPython session, based on path

e.g. to embed links to files that were generated in the IPython notebook
under ``my/data``, you would do::

    local_files = FileLinks("my/data")
    display(local_files)

or in the HTML notebook, just::

    FileLinks("my/data")
Nc	                 "   [        U5      (       a  [        SU-  5      eX0l        UR                  S5      nXl        X l        X@l        XPl        U=(       d    U R                  5       U l	        U=(       d    U R                  5       U l        Xl        g)a  
See :class:`FileLink` for the ``path``, ``url_prefix``,
``result_html_prefix`` and ``result_html_suffix`` parameters.

included_suffixes : list
  Filename suffixes to include when formatting output [default: include
  all files]

notebook_display_formatter : function
  Used to format links for display in the notebook. See discussion of
  formatter functions below.

terminal_display_formatter : function
  Used to format links for display in the terminal. See discussion of
  formatter functions below.

Formatter functions must be of the form::

    f(dirname, fnames, included_suffixes)

dirname : str
  The name of a directory
fnames : list
  The files in that directory
included_suffixes : list
  The file suffixes that should be included in the output (passing None
  meansto include all suffixes in the output in the built-in formatters)
recursive : boolean
  Whether to recurse into subdirectories. Default is True.

The function should return a list of lines that will be printed in the
notebook (if passing notebook_display_formatter) or the terminal (if
passing terminal_display_formatter). This function is iterated over for
each directory in self.path. Default formatters are in place, can be
passed here to support alternative formatting.

zDCannot display a file using FileLinks. Use FileLink to display '%s'./N)r   r$   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   s	            r0   r(   FileLinks.__init__  s    \ $<< .045 6 6!2{{3	$"4"4 (Q4+O+O+Q 	' (Q4+O+O+Q 	' #r2   c                 $   ^^^^ SUUUU4S jjnU$ )a  generate built-in formatter function

this is used to define both the notebook and terminal built-in
 formatters as they only differ by some wrapper text for each entry

dirname_output_format: string to use for formatting directory
 names, dirname will be substituted for a single "%s" which
 must appear in this string
fname_output_format: string to use for formatting file names,
 if a single "%s" appears in the string, fname will be substituted
 if two "%s" appear in the string, the path to fname will be
  substituted for the first and fname will be substituted for the
  second
fp_format: string to use for formatting filepaths, must contain
 exactly two "%s" and the dirname will be substituted for the first
 and fname will be substituted for the second
c                   > / n/ nU HF  n[        [        X5      5      (       d  M  Ub  [        U5      S   U;   d  M5  UR                  U5        MH     [	        U5      S:X  a   U$ T	U -  nUR                  U5        U H,  nTX4-  nTb  T" U5      n T
Xu4-  nUR                  U5        M.     U$ ! [
         a    T
U-  n N(f = f)NrU   r   )r   r   r   appendrZ   rl   )dirnamefnamesr   resultdisplay_fnamesfnamedirname_output_linerN   fname_output_linedirname_output_formatfname_output_format
fp_cleaner	fp_formats            r0   rh   +FileLinks._get_display_formatter.<locals>.f  s    F  N4.//)1 *.??$++E2	   >"a' " M '<g&E#12+E"g_4B!-'^H,?2+,M) MM"34 , M	 % H,?%,G)Hs   B..C ?C r   r   )r,   r   r   r   r   rh   s    ```` r0   _get_display_formatter FileLinks._get_display_formatter  s    (	 	@ r2   c                     U R                   S-   U R                  -   nU R                   U-   U R                  -   U R                  -   nU R                  S-   n[        S:X  a  S nOSnU R                  UUUU5      $ )z9generate function to use for notebook formatting
        %s/%s/%s\c                 &    U R                  SS5      $ )Nr   r   )replace)rN   s    r0   r   =FileLinks._get_notebook_display_formatter.<locals>.fp_cleanerE  s     zz$s++r2   N)r   r   r   r   r   r   )r,   spacerr   r   r   r   s         r0   r   )FileLinks._get_notebook_display_formatter9  s    
 
	 	 5	(4+B+B	B 	 
	 	 6	)D,>,>	>AXAX	X 	OOg-	$;, J**+@+>+4+57 	7r2   c                 :    SnUS-   nSnU R                  UUU5      $ )z9generate function to use for terminal formatting
        r   z%sr   )r   )r,   r   r   r   r   s        r0   r   )FileLinks._get_terminal_display_formatterR  s5     !&$tm	**+@+>+46 	6r2   c                 :   / nU R                   (       a  [        [        U R                  5      5      nO[	        [        U R                  5      5      /nUR                  5         U H$  u  p4nXR                  X5U R                  5      -  nM&     SR                  U5      $ )N
)	r   r   r
   r   nextsortr   r   r   r,   result_lines
walked_dirr   subdirsr   s         r0   r   FileLinks._format_path^  sx    >>d499o.JtDII/0J(2$Gf;;GTMcMcddL )3yy&&r2   c                 :   / nU R                   (       a  [        [        U R                  5      5      nO[	        [        U R                  5      5      /nUR                  5         U H$  u  p4nXR                  X5U R                  5      -  nM&     SR                  U5      $ )z0return newline-separated absolute paths
        r   )	r   r   r
   r   r  r  r   r   r   r  s         r0   r   FileLinks.__repr__i  sz     >>d499o.JtDII/0J(2$Gf;;GTMcMcddL )3yy&&r2   )r   r   r   r   r   r   r   r   )r   Nr   r   NNTr   )z&nbsp;&nbsp;)z  )r   r   r   r   r   r(   r   r   r   r   r   r   r   r2   r0   r   r     sO     #'$&$*,0,0?#D QU4n 0>74 04
6	''r2   r   c                   H   ^  \ rS rSrSrS	U 4S jjrS rS rS rS r	Sr
U =r$ )
r   iw  a  Display syntax-highlighted source code.

This uses Pygments to highlight the code for HTML and Latex output.

Parameters
----------
data : str
    The code as a string
url : str
    A URL to fetch the code from
filename : str
    A local filename to load the code from
language : str
    The short name of a Pygments lexer to use for highlighting.
    If not specified, it will guess the lexer based on the filename
    or the code. Available lexers: http://pygments.org/docs/lexers/
c                 .   > X@l         [        TU ]	  XUS9  g )Nr    )languager'   r(   )r,   r!   r"   r#   r  r/   s        r0   r(   Code.__init__  s     dh?r2   c                     U R                   (       a  SSKJn  U" U R                   5      $ U R                  (       a  SSKJn  U" U R                  5      $ SSKJn  U" U R                  5      $ )Nr   )get_lexer_by_name)get_lexer_for_filename)guess_lexer)r  pygments.lexersr  r#   r  r  r!   )r,   r  r  r  s       r0   
_get_lexerCode._get_lexer  sF    ==9$T]]33]]>)$--883tyy))r2   c                     U R                   $ r   )r!   r   s    r0   r   Code.__repr__  s    yyr2   c                     SSK Jn  SSKJn  U" 5       nSR	                  UR                  S5      5      nXA" U R                  U R                  5       U5      -   $ )Nr   	highlight)HtmlFormatterz<style>{}</style>z.output_html)pygmentsr  pygments.formattersr  r|   get_style_defsr!   r  )r,   r  r  fmtstyles        r0   r   Code._repr_html_  sI    &5o#**3+=+=n+MNyDOO,=sCCCr2   c                 h    SSK Jn  SSKJn  U" U R                  U R                  5       U" 5       5      $ )Nr   r  )LatexFormatter)r  r  r  r"  r!   r  )r,   r  r"  s      r0   _repr_latex_Code._repr_latex_  s%    &6DOO$5~7GHHr2   )r  )NNNN)r   r   r   r   r   r(   r  r   r   r#  r   r   r   s   @r0   r   r   w  s*    "@	*DI Ir2   r   N)r   htmlr   r   os.pathr   r   r   r   r   r	   osr
   r   r   IPython.core.displayr   r   typingr   r   r   __all__r   r   r   r   r   r   r   r   r   r2   r0   <module>r+     s    ' B B " " A , ,,pM pd)
 )
X)6 )VG GKV K @" @"D' 'D.I .Ir2   