wL i_ dZddlmZddlmZmZmZmZm Z m Z ddl m Z m Z mZddlmZmZddlmZmZmZgdZGdd eZGd d ZGd d eZGddeZGddeZGddZGddeZGddeZy)zMVarious display related classes. Authors : MinRK, gregcaporaso, dannystaple )escape)existsisfilesplitextabspathjoinisdir)walksepfsdecode) DisplayObjectTextDisplayObject)TupleIterableOptional)AudioIFrame YouTubeVideo VimeoVideoScribdDocumentFileLink FileLinksCodeceZdZdZdZdddfd ZfdZedZede e e ffd Z ed Z ed Zd Zd ZdZdZdZxZS)ra 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) 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) 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^|| | td|dur | td| |durd|_nd|_||_||_tt |||||jEt|jts*| tdt j||||_yyy)Nz6No audio data found. Expecting filename, url, or data.Fz,No url found. Expecting url when embed=FalseTdataurlfilenamezKrate must be specified when data is a numpy array or list of audio samples.) ValueErrorembedautoplayrsuperr__init__r isinstancebytes _make_wav) selfr r"r!r$rater% normalizer __class__s Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/IPython/lib/display.pyr'zAudio.__init__ps    UV V E>ckKL L ?uD0DJDJ  $ eT#3#J 99 DIIu)E| !noodI>DI*F cddl}|jrtt||j $|j |j d|_y|j$|j |jd|_yd|_y)z%Reload the raw data from file or URL.rNz audio/wav) mimetypesr$r&rreloadr" guess_typemimetyper!)r+r2r.s r/r3z Audio.reloadsk :: % % ' == $%00?BDM XX !%00:1=DM'DMr0cddlm}ddl} tj ||\}}|}|j|d}|j||j||jd|jdd|j||j} |j| S#t $rtj ||\}}YwxYw)z- Transform a numpy array to a PCM bytestring r)BytesIONwb)modeNONE)ior7waver"_validate_and_normalize_with_numpy ImportError%_validate_and_normalize_without_numpyopen setnchannels setframerate setsampwidth setcomptype writeframesgetvalueclose) r r,r-r7r=scalednchanfpwaveobjvals r/r*zAudio._make_wavs  Y!DDT9UMFEY))BD))U#T"QF6*F#kkm   Y!GGiXMFE YsB77"CCreturncddl}|j|t}t|jdk(rd}nMt|jdk(r*|jd}|j j }n td|j|j|}tj||}||z dz}|jdj|fS)Nr)dtyper:z*Array audio input must be a 1D or 2D arrayzz(Audio._validate_and_normalize_with_numpysxxEx* tzz?a E _ ! JJqME66<<>DIJ Jrvvd|, $>>}iX,,u4}}T"**,e33r0c ddl}ddl}|jd|} tt|Dcgc] }t |c}}t j||}|jd|Dcgc]}t||z dzc}}|jdk(r|jd} |j| fScc}w#t $r}t d|d}~wwxYwcc}w)Nrfz@Only lists of mono audio are supported if numpy is not installedhrRbigrQ) rTsysrUrZr[ TypeErrorrr\int byteorderbyteswapr^) r r-rTrfxr`erarIrJs r/r@z+Audio._validate_and_normalize_without_numpys{{3% >!#t&M %>>}iXSRV"WQ3q+?'?%'G#H"WX ==E ! OO ~~&&'= >67<= > > #Xs-CB? C-C! ?C C CCc2|s|dkDr td|r|SdS)NrQz9Audio data must be between -1 and 1 when normalize=False.)r#)r`r-s r/r\zAudio._get_normalization_factors%]Q.XY Y )}0q0r0cti}|jr|j|d<|r|j|fS|jS)z@shortcut for returning metadata with url information, if definedr!)r!r )r+mds r/_data_and_metadatazAudio._data_and_metadatas6  88BuI 99b= 99 r0cd}|j|j|j|j|j S)Nz )srctyper%r)formatsrc_attrr5 autoplay_attrelement_id_attr)r+rrs r/ _repr_html_zAudio._repr_html_sF zzdmmoDMMDL^L^L`%)%9%9%;= =r0cddl}|jrU|jI|j|jj dx}}dj |j |S|j |jSy)Nrasciizdata:{type};base64,{base64})rsbase64)r{r$r b64encodedecodertr5r!)r+r{r s r/ruzAudio.src_attrsr ::4990 **4995<r@r\rprxrurvrw __classcell__r.s@r/rrs[xK? ?( (,4uUCZ?P44*''&11 =  r0rc6eZdZdZdZ ddeeefdZdZ y)rzA Generic class to embed an iframe in an IPython notebook z Nextrasc R|g}||_||_||_||_||_yN)rrwidthheightrparams)r+rrrrrkwargss r/r'zIFrame.__init__s1 >F    r0c |jrddlm}d||jz}nd}|jj |j |j |j|dj|jS)zreturn the embed iframer) urlencode?r| )rrrrrr) r urllib.parseriframertrrrrrr)r+rrs r/rxzIFrame._repr_html_sh ;; .9T[[11FF{{!!**;;88DKK( "  r0r) rrrrrrrstrr'rxr0r/rrs0  FEI *28C=*A   r0rc*eZdZdZdfd ZdZxZS)raClass 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 ||_dj|}|r2t|jdgdgz}|j d|t t ||||fi|y)Nz!https://www.youtube.com/embed/{0}rzallow="autoplay"rQ)r%r)idrtlistgetupdater&rr') r+rrrallow_autoplayrrrrr.s r/r'zYouTubeVideo.__init__Isc188< &**Xr237I6JJF MM1VM 4 lD*3vHHr0cddlm} |dj|jj S#t $rYywxYw)Nr)urlopenz-https://img.youtube.com/vi/{id}/hqdefault.jpg)r)urllib.requestrrtrreadIOError)r+rs r/ _repr_jpeg_zYouTubeVideo._repr_jpeg_QsF* JQQUYU\U\Q]^cce e  s/8 AA),F)rrrrr'rrrs@r/rr/s2Ir0rc$eZdZdZdfd ZxZS)rzY Class for embedding a Vimeo video in an IPython session, based on its video id. c Tdj|}tt||||fi|y)Nz"https://player.vimeo.com/video/{0})rtr&rr'r+rrrrrrr.s r/r'zVimeoVideo.__init___s+ 0 7 7 ; j$(eVFvFr0rrrrrrr'rrs@r/rrZsGGr0rc$eZdZdZdfd ZxZS)ra 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 Tdj|}tt||||fi|y)Nz)https://www.scribd.com/embeds/{0}/content)rtr&rr'rs r/r'zScribdDocument.__init__os+ 7 > >r B nd,S%J6Jr0rrrs@r/rrcs KKr0rc4eZdZdZdZ ddZdZdZdZy) raGClass 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#%sct|rtd|zt||_||_||_||_y)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: '
'] zICannot display a directory using FileLink. Use FileLinks to display '%s'.N)r r#r path url_prefixresult_html_prefixresult_html_suffix)r+rrrrs r/r'zFileLink.__init__sG$ ;/1567 7TN $"4"4r0c dj|jt|jg}dj|j|j |t|jdfz|j gS)Nr|F)quote)rr html_escaperr html_link_strr)r+rKs r/ _format_pathzFileLink._format_pathsk WWdoo{499'=> ?ww//**TYYe!DEF//12 2r0cjt|jsd|jzS|jS)z!return html link to file zxPath (%s) doesn't exist. It may still be in the process of being generated, or you may have the incorrect path.)rrrrs r/rxzFileLink._repr_html_s9dii &)- 2 3   ""r0c,t|jS)z%return absolute path to file )rrrs r/__repr__zFileLink.__repr__styy!!r0N)r|r|
) rrrrrr'rrxrrr0r/rrss- :M$&$* 542 #"r0rcPeZdZdZ d dZ d dZ d dZ d dZdZdZ y) raNClass 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 t|rtd|z||_|jd}||_||_||_||_|xs|j|_ |xs|j|_ ||_ y)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) rr#included_suffixesrstriprrrr_get_notebook_display_formatternotebook_display_formatter_get_terminal_display_formatterterminal_display_formatter recursive) r+rrrrrrrrs r/r'zFileLinks.__init__s\ $<.0456 6!2{{3 $"4"4( Q4+O+O+Q '( Q4+O+O+Q '#r0c dfd }|S)akgenerate 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 cjg}g}|D]<}tt||s|t|d|vs,|j|>t |dk(r |S |z}|j||D],} ||fz}  |} ||fz}|j|.|S#t $r |z}Y%wxYw)NrQr)rrrappendrVrg) dirnamefnamesrresultdisplay_fnamesfnamedirname_output_linerKfname_output_linedirname_output_formatfname_output_format fp_cleaner fp_formats r/rcz+FileLinks._get_display_formatter..fsF N 34./)1 *.??$++E2  3 >"a'"M'.fp_cleanerEszz$s++r0N)rrrrr r)r+spacerrrrrs r/rz)FileLinks._get_notebook_display_formatter9s  5 (4+B+B B   6 )D,>,> >AXAX X OOg- $; , J**+@+>+4+57 7r0c:d}|dz}d}|j|||S)z: generate function to use for terminal formatting rz%sr)r)r+rrrrs r/rz)FileLinks._get_terminal_display_formatterRs5!&$tm **+@+>+46 6r0c2g}|jrtt|j}nt t|jg}|j |D]&\}}}||j |||jz }(dj|S)N ) rrr rnextsortrrrr+ result_lines walked_dirrsubdirsrs r/rzFileLinks._format_path^s >>d499o.JtDII/0J(2 e $GWf D;;GVTMcMcd dL eyy&&r0c2g}|jrtt|j}nt t|jg}|j |D]&\}}}||j |||jz }(dj|S)z0return newline-separated absolute paths r) rrr rrrrrrrs r/rzFileLinks.__repr__is >>d499o.JtDII/0J(2 e $GWf D;;GVTMcMcd dL eyy&&r0)r|Nr|rNNTr)z   )z ) rrrrr'rrrrrrr0r/rrsO #'$&$*,0,0?#DQU4n0>7404 6 ' 'r0rc<eZdZdZdfd ZdZdZdZdZxZ S)raDisplay 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/ c8||_t| |||y)Nr)languager&r')r+r r!r"rr.s r/r'z Code.__init__s   dh?r0c|jrddlm}||jS|jrddlm}||jSddlm}||j S)Nr)get_lexer_by_name)get_lexer_for_filename) guess_lexer)rpygments.lexersrr"rrr )r+rrrs r/ _get_lexerzCode._get_lexersF == 9$T]]3 3 ]] >)$--8 8 3tyy) )r0c|jSr)r rs r/rz Code.__repr__s yyr0cddlm}ddlm}|}dj |j d}|||j |j|zS)Nr highlight) HtmlFormatterzz .output_html)pygmentsrpygments.formattersrrtget_style_defsr r)r+rrfmtstyles r/rxzCode._repr_html_sI&5o#**3+=+=n+MNyDOO,=sCCCr0chddlm}ddlm}||j|j |S)Nrr)LatexFormatter)rrrrr r)r+rrs r/ _repr_latex_zCode._repr_latex_s%&6DOO$5~7GHHr0)NNNN) rrrrr'rrrxrrrs@r/rrws$"@ *DIr0rN)rhtmlrros.pathrrrrrr osr r r IPython.core.displayr rtypingrrr__all__rrrrrrrrrr0r/rs'BB""A,, ,pMpd) ) X)6)VGGKVK @"@"D''D.I .Ir0