L i UddlmZddlZddlZddlmZddlmZddlm Z m Z m Z m Z m Z ddlmZmZmZddlmZmZddlmZdd lmZdd lmZdd lmZdd lmZ dd l!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(e rddlm)Z)ddl*mZ+ddl,m-Z-e e.ee/ej`ejbejdddfZ3de4d<e.eze/zej`ze5e.e.eze/zej`zfzdzZ6de4d<e7e8zeze.zZ9de4d<dZ:de4d<GddZ;dZ d* d+d"Z? d,d#Z@d-d$ZAd.d%ZBd/d&ZC d0 d1d'ZDy)2) annotationsN) timedelta)Path) TYPE_CHECKINGFinal TypeAliasUnioncast)runtime type_utilurl_util)WidthWithoutContentvalidate_width)process_subtitle_data)compute_and_register_element_id)StreamlitAPIException)Audio)Video) WidthConfig)caching)gather_metrics)time_to_seconds)Any)typing)DeltaGeneratornpt.NDArray[Any]r MediaData SubtitleData MediaTimeaFailed to convert '{param_name}' to a timedelta. Please use a string in a format supported by [Pandas Timedelta constructor](https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html), e.g. `"10s"`, `"15 seconds"`, or `"1h23s"`. Got: {param_value}rTIMEDELTA_PARSE_ERROR_MESSAGEc eZdZed d dddddd d dZed d ddddddd dd Zedd Zy) MediaMixinaudioNFstretch) sample_rateend_timeloopautoplaywidthc ~t||\}}t|t} tj|d} | r | t d| s||j jd|j j} t|j | | |||||||| |j jd| S)a3Display an audio player. Parameters ---------- data : str, Path, bytes, BytesIO, numpy.ndarray, or file The audio to play. This can be one of the following: - A URL (string) for a hosted audio file. - A path to a local audio file. The path can be a ``str`` or ``Path`` object. Paths can be absolute or relative to the working directory (where you execute ``streamlit run``). - Raw audio data. Raw data formats must include all necessary file headers to match the file format specified via ``format``. If ``data`` is a NumPy array, it must either be a 1D array of the waveform or a 2D array of shape (C, S) where C is the number of channels and S is the number of samples. See the default channel order at http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx format : str The MIME type for the audio file. This defaults to ``"audio/wav"``. For more information about MIME types, see https://www.iana.org/assignments/media-types/media-types.xhtml. start_time : int, float, timedelta, str, or None The time from which the element should start playing. This can be one of the following: - ``None`` (default): The element plays from the beginning. - An ``int`` or ``float`` specifying the time in seconds. ``float`` values are rounded down to whole seconds. - A string specifying the time in a format supported by `Pandas' Timedelta constructor `_, e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``. - A ``timedelta`` object from `Python's built-in datetime library `_, e.g. ``timedelta(seconds=70)``. sample_rate : int or None The sample rate of the audio data in samples per second. This is only required if ``data`` is a NumPy array. end_time : int, float, timedelta, str, or None The time at which the element should stop playing. This can be one of the following: - ``None`` (default): The element plays through to the end. - An ``int`` or ``float`` specifying the time in seconds. ``float`` values are rounded down to whole seconds. - A string specifying the time in a format supported by `Pandas' Timedelta constructor `_, e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``. - A ``timedelta`` object from `Python's built-in datetime library `_, e.g. ``timedelta(seconds=70)``. loop : bool Whether the audio should loop playback. autoplay : bool Whether the audio file should start playing automatically. This is ``False`` by default. Browsers will not autoplay audio files if the user has not interacted with the page by clicking somewhere. width : "stretch" or int The width of the audio player element. This can be one of the following: - ``"stretch"`` (default): The width of the element matches the width of the parent container. - An integer specifying the width in pixels: The element has a fixed width. If the specified width is greater than the width of the parent container, the width of the element matches the width of the parent container. Examples -------- To display an audio player for a local file, specify the file's string path and format. >>> import streamlit as st >>> >>> st.audio("cat-purr.mp3", format="audio/mpeg", loop=True) .. output:: https://doc-audio-purr.streamlit.app/ height: 250px You can also pass ``bytes`` or ``numpy.ndarray`` objects to ``st.audio``. >>> import streamlit as st >>> import numpy as np >>> >>> audio_file = open("myaudio.ogg", "rb") >>> audio_bytes = audio_file.read() >>> >>> st.audio(audio_bytes, format="audio/ogg") >>> >>> sample_rate = 44100 # 44100 samples per second >>> seconds = 2 # Note duration of 2 seconds >>> frequency_la = 440 # Our played note will be 440 Hz >>> # Generate array with seconds*sample_rate steps, ranging between 0 and seconds >>> t = np.linspace(0, seconds, seconds * sample_rate, False) >>> # Generate a 440 Hz sine wave >>> note_la = np.sin(frequency_la * t * 2 * np.pi) >>> >>> st.audio(note_la, sample_rate=sample_rate) .. output:: https://doc-audio.streamlit.app/ height: 865px numpy.ndarrayz=`sample_rate` must be specified when `data` is a numpy array.zGWarning: `sample_rate` will be ignored since data is not a numpy array.r)r#) _parse_start_time_end_timer AudioProtor is_typerdgwarning_get_delta_path_strmarshall_audio_enqueue) selfdataformat start_timer%r&r'r(r) audio_protois_data_numpy_array coordinatess ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/streamlit/elements/media.pyr#zMediaMixin.audioFst :*hO Hu l '//oF ;#6'O #{'> GGOO gg113  GG          ww55video) subtitlesr&r'r(mutedr)ct||\}}t| t} |jj } t |j| | |||||||||  |jj d| S)azDisplay a video player. Parameters ---------- data : str, Path, bytes, io.BytesIO, numpy.ndarray, or file The video to play. This can be one of the following: - A URL (string) for a hosted video file, including YouTube URLs. - A path to a local video file. The path can be a ``str`` or ``Path`` object. Paths can be absolute or relative to the working directory (where you execute ``streamlit run``). - Raw video data. Raw data formats must include all necessary file headers to match the file format specified via ``format``. format : str The MIME type for the video file. This defaults to ``"video/mp4"``. For more information about MIME types, see https://www.iana.org/assignments/media-types/media-types.xhtml. start_time : int, float, timedelta, str, or None The time from which the element should start playing. This can be one of the following: - ``None`` (default): The element plays from the beginning. - An ``int`` or ``float`` specifying the time in seconds. ``float`` values are rounded down to whole seconds. - A string specifying the time in a format supported by `Pandas' Timedelta constructor `_, e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``. - A ``timedelta`` object from `Python's built-in datetime library `_, e.g. ``timedelta(seconds=70)``. subtitles : str, bytes, Path, io.BytesIO, or dict Optional subtitle data for the video, supporting several input types: - ``None`` (default): No subtitles. - A string, bytes, or Path: File path to a subtitle file in ``.vtt`` or ``.srt`` formats, or the raw content of subtitles conforming to these formats. Paths can be absolute or relative to the working directory (where you execute ``streamlit run``). If providing raw content, the string must adhere to the WebVTT or SRT format specifications. - io.BytesIO: A BytesIO stream that contains valid ``.vtt`` or ``.srt`` formatted subtitle data. - A dictionary: Pairs of labels and file paths or raw subtitle content in ``.vtt`` or ``.srt`` formats to enable multiple subtitle tracks. The label will be shown in the video player. Example: ``{"English": "path/to/english.vtt", "French": "path/to/french.srt"}`` When provided, subtitles are displayed by default. For multiple tracks, the first one is displayed by default. If you don't want any subtitles displayed by default, use an empty string for the value in a dictrionary's first pair: ``{"None": "", "English": "path/to/english.vtt"}`` Not supported for YouTube videos. end_time : int, float, timedelta, str, or None The time at which the element should stop playing. This can be one of the following: - ``None`` (default): The element plays through to the end. - An ``int`` or ``float`` specifying the time in seconds. ``float`` values are rounded down to whole seconds. - A string specifying the time in a format supported by `Pandas' Timedelta constructor `_, e.g. ``"2 minute"``, ``"20s"``, or ``"1m14s"``. - A ``timedelta`` object from `Python's built-in datetime library `_, e.g. ``timedelta(seconds=70)``. loop : bool Whether the video should loop playback. autoplay : bool Whether the video should start playing automatically. This is ``False`` by default. Browsers will not autoplay unmuted videos if the user has not interacted with the page by clicking somewhere. To enable autoplay without user interaction, you must also set ``muted=True``. muted : bool Whether the video should play with the audio silenced. This is ``False`` by default. Use this in conjunction with ``autoplay=True`` to enable autoplay without user interaction. width : "stretch" or int The width of the video player element. This can be one of the following: - ``"stretch"`` (default): The width of the element matches the width of the parent container. - An integer specifying the width in pixels: The element has a fixed width. If the specified width is greater than the width of the parent container, the width of the element matches the width of the parent container. Example ------- >>> import streamlit as st >>> >>> video_file = open("myvideo.mp4", "rb") >>> video_bytes = video_file.read() >>> >>> st.video(video_bytes) .. output:: https://doc-video.streamlit.app/ height: 700px When you include subtitles, they will be turned on by default. A viewer can turn off the subtitles (or captions) from the browser's default video control menu, usually located in the lower-right corner of the video. Here is a simple VTT file (``subtitles.vtt``): >>> WEBVTT >>> >>> 0:00:01.000 --> 0:00:02.000 >>> Look! >>> >>> 0:00:03.000 --> 0:00:05.000 >>> Look at the pretty stars! If the above VTT file lives in the same directory as your app, you can add subtitles like so: >>> import streamlit as st >>> >>> VIDEO_URL = "https://example.com/not-youtube.mp4" >>> st.video(VIDEO_URL, subtitles="subtitles.vtt") .. output:: https://doc-video-subtitles.streamlit.app/ height: 700px See additional examples of supported subtitle input types in our `video subtitles feature demo `_. .. note:: Some videos may not display if they are encoded using MP4V (which is an export option in OpenCV), as this codec is not widely supported by browsers. Converting your video to H.264 will allow the video to be displayed in Streamlit. See this `StackOverflow post `_ or this `Streamlit forum post `_ for more information. r,r>)r-r VideoProtor0r2marshall_videor4) r5r6r7r8r?r&r'r(r@r) video_protor;s r<r>zMediaMixin.videos~ :*hO Hu l gg113  GG           ww55r=ctd|S)zGet our DeltaGenerator.r)r )r5s r<r0z MediaMixin.dgs$d++r=) audio/wavr)r6rr7strr8rr% int | Noner&MediaTime | Noner'boolr(rJr)rreturnr) video/mp4r)r6rr7rGr8rr?rr&rIr'rJr(rJr@rJr)rrKr)rKr)__name__ __module__ __qualname__rr#r>propertyr0r=r<r"r"EsZG" ! W6 #'%)%.W6W6W6 W6  W6#W6W6W6#W6 W6W6rG" ! q6 #'%)%.q6q6q6 q6  q6#q6q6q6q6#q6 q6q6f,,r=r"a^((https?://(?:www\.)?(?:m\.)?youtube\.com))/((?:oembed\?url=https?%3A//(?:www\.)youtube.com/watch\?(?:v%3D)(?P[\w\-]{10,20})&format=json)|(?:attribution_link\?a=.*watch(?:%3Fv%3D|%3Fv%3D)(?P[\w\-]{10,20}))(?:%26feature.*))|(https?:)?(\/\/)?((www\.|m\.)?youtube(-nocookie)?\.com\/((watch)?\?(app=desktop&)?(feature=\w*&)?v=|embed\/|v\/|e\/)|youtu\.be\/)(?P[\w\-]{10,20}) YOUTUBE_REctjt|}|r<|jdxs$|jdxs|jd}d|Sy)aReturn whether URL is any kind of YouTube embed or watch link. If so, reshape URL into an embed link suitable for use in an iframe. If not a YouTube URL, return None. Parameters ---------- url : str Example ------- >>> print(_reshape_youtube_url("https://youtu.be/_T8LGqJtuGc")) .. output:: https://www.youtube.com/embed/_T8LGqJtuGc video_id_1 video_id_2 video_id_3zhttps://www.youtube.com/embed/N)rematchrRgroup)urlrXcodes r<_reshape_youtube_urlr\s\" HHZ %E KK % ){{<( ){{<( 0v66 r=c|yt|ttfr|}nt|tr t|}nt|tj r"|j d|j}nt|tjtjfr'|j d|j}|y|}n>tj|dr|j}ntdt|t!j"rNt!j$j&j)|||}t+j,|||||_yd}||_y)aFill audio or video proto based on contents of data. Given a string, check if it's a url; if so, send it out without modification. Otherwise assume strings are filenames and let any OS errors raise. Load data either from file or through bytes-processing methods into a MediaFile object. Pack proto with generated Tornado-based URL. (When running in "raw" mode, we won't actually load data into the MediaFileManager, and we'll return an empty URL.) Nrr+zInvalid binary data format: ) isinstancerGbytesrioBytesIOseekgetvalue RawIOBaseBufferedReaderreadr r/tobytes RuntimeErrortyper exists get_instancemedia_file_mgraddrsave_media_datarZ)r;protor6mimetypedata_or_filename read_datafile_urls r<_marshall_av_mediarus(& |$e % D$ t9 D"** % ! ==? D2<<):):; < ! IIK   $   4 1<<>9$t*FGG~~'')88<< h    0(KH EIEIr=c |dks|||kr td||_| |_|||_||_t } t | tr| | _nd| _ |jj| tjj|_t |t r t#|}t |t"r_t%j&|drHt)|x} r3| |_tjj,|_|r!td||_nt/|||||rg}t |t"t0t2j4t fr|j7d|fnHt |t8r |j;|j=ntd t|d |D]E\}}|j>jA}|xsd |_!|d |d } tE||||_G| r.| |_%tMddd||j*||||| | |  |_'yy#tFtHf$r}td||d}~wwxYw)ar Marshalls a video proto, using url processors as needed. Parameters ---------- coordinates : str proto : the proto to fill. Must have a string field called "data". data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with io.open(). Raw video data or a string with a URL pointing to the video to load. Includes support for YouTube URLs. If passing the raw data, this must include headers and any other bytes required in the actual file. mimetype : str The mime type for the video file. Defaults to 'video/mp4'. See https://tools.ietf.org/html/rfc4281 for more info. start_time : int The time from which this element should start playing. (default: 0) subtitles: str, dict, or io.BytesIO Optional subtitle data for the video, supporting several input types: - None (default): No subtitles. - A string: File path to a subtitle file in '.vtt' or '.srt' formats, or the raw content of subtitles conforming to these formats. If providing raw content, the string must adhere to the WebVTT or SRT format specifications. - A dictionary: Pairs of labels and file paths or raw subtitle content in '.vtt' or '.srt' formats. Enables multiple subtitle tracks. The label will be shown in the video player. Example: {'English': 'path/to/english.vtt', 'French': 'path/to/french.srt'} - io.BytesIO: A BytesIO stream that contains valid '.vtt' or '.srt' formatted subtitle data. When provided, subtitles are displayed by default. For multiple tracks, the first one is displayed by default. Not supported for YouTube videos. end_time: int The time at which this element should stop playing loop: bool Whether the video should loop playback. autoplay: bool Whether the video should start playing automatically. Browsers will not autoplay video files if the user has not interacted with the page yet, for example by clicking on the page while it loads. To enable autoplay without user interaction, you can set muted=True. Defaults to False. muted: bool Whether the video should play with the audio silenced. This can be used to enable autoplay without user interaction. Defaults to False. width: int or "stretch" The width of the video player. This can be one of the following: - An int: The width in pixels, e.g. 200 for a width of 200 pixels. - "stretch": The default value. The video player stretches to fill available space in its container. rNz,Invalid start_time and end_time combination.Thttphttpsr6allowed_schemasz/Subtitles are not supported for YouTube videos.defaultz%Unsupported data type for subtitles: z/. Only str (file paths) and dict are supported.r^z [subtitle]z)Failed to process the provided subtitle: r>F) user_keykey_as_main_identityr0rZrqr8r&r'r(r@r))(rr8r@r&r'rr_int pixel_width use_stretch width_configCopyFromrBTypeNATIVErjrrGr is_urlr\rZYOUTUBE_IFRAMErur`rarbappenddictextenditemsr?rnlabelr TypeError ValueErrorr(rid)r0r;rpr6rqr8r?r&r'r(r@r)r youtube_urlsubtitle_itemsr subtitle_datasubsubtitle_coordinates original_errs r<rCrCs`~A~(.8z3I#$RSS!EEK!EJ=L%#(  #'    -''EJ$4y$ 7"/t4 4; 4#EI#77EJ+EEI;tX>LN i#ubjj$!? @  ! !9i"8 9  4 (  ! !)//"3 4'7Y7HI@A  %3 $ E=//%%'C CI'2])E7!#D  $/(- $&!2 !& !  z* $+?wG#$ $s1H66IIIcN t|d}|tt|} t|d}| t|}||fS#ttf$r$tj d|}t|dwxYw#t$r$tj d|}t|dwxYw)z5Parse start_time and end_time and return them as int.F)coerce_none_to_infNr8) param_name param_valuer&)rrrrr r7)r8r&maybe_start_time error_msgs r<r-r-s 9*:%P  # )* 9"8F  8}H x ! ": .9188#9 $I.D8 9 !9188!x9 $I.D8 9s AA73A47-B$c&ddl}|j|t}t|jdk(rd}nMt|jdk(r*|jd}|j j }n td|jdk(r+|j|jj|fS|j|j|}||z dz}|j|j}|j|fS)aValidates and normalizes numpy array data. We validate numpy array shape (should be 1d or 2d) We normalize input data to int16 [-32768, 32767] range. Parameters ---------- data : numpy array numpy array to be validated and normalized Returns ------- Tuple of (bytes, int) (bytes, nchan) where - bytes : bytes of normalized numpy array converted to int16 - nchan : number of channels for audio signal. 1 for mono, or 2 for stereo. rN)dtypez1Numpy array audio input must be a 1D or 2D array.i)numpyarrayfloatlenshapeTravelrsizeastypeint16rhmaxabs)r6nptransformed_datanchan max_abs_valuenp_array scaled_datas r<_validate_and_normalizers()+$e)D  ! !"a'  # # $ ) !&&q)+--335#$WXX!&&rxx088:EAA&(ffRVV4D-E&FM !=0E9H//"((+K    % ''r=cddl}t|\}}tj5}|j |d5}|j ||j ||jd|jdd|j||jcdddcdddS#1swYnxYwdddy#1swYyxYw)z Transform a numpy array to a PCM bytestring. We use code from IPython display module to convert numpy array to wave bytes https://github.com/ipython/ipython/blob/1015c392f3d50cf4ff3e9f29beede8c1abfdcb2a/IPython/lib/display.py#L146 rNwb)moderNONE) waverrarbopen setnchannels setframerate setsampwidth setcomptype writeframesrd)r6r%rscaledrfpwaveobjs r< _make_wavrs+D1MFE TYYrY5U#[)QFF+F#{{} s#C A&B4! C 4B= 9C  Ccbtj|dr|ttd||}|S)z:Convert data to wav bytes if the data type is numpy array.r+r)r r/rr )r6r%s r<_maybe_convert_to_wav_bytesrs0/K4K0$7E Kr=c ||_|||_||_t} t | t r| | _nd| _|jj| t |tr t|}t |trtj|dr||_nt||}t!||||| r.| |_t%ddd||j|||||| |  |_yy)aMarshalls an audio proto, using data and url processors as needed. Parameters ---------- coordinates : str proto : The proto to fill. Must have a string field called "url". data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with io.open() Raw audio data or a string with a URL pointing to the file to load. If passing the raw data, this must include headers and any other bytes required in the actual file. mimetype : str The mime type for the audio file. Defaults to "audio/wav". See https://tools.ietf.org/html/rfc4281 for more info. start_time : int The time from which this element should start playing. (default: 0) sample_rate: int or None Optional param to provide sample_rate in case of numpy array end_time: int The time at which this element should stop playing loop: bool Whether the audio should loop playback. autoplay : bool Whether the audio should start playing automatically. Browsers will not autoplay audio files if the user has not interacted with the page yet. width: int or "stretch" The width of the audio player. This can be one of the following: - An int: The width in pixels, e.g. 200 for a width of 200 pixels. - "stretch": The default value. The audio player stretches to fill available space in its container. NTrwrzr#F) r~rr0rZrqr8r%r&r'r(r))r8r&r'rr_rrrrrrrGr rrZrrur(rr) r0r;rpr6rqr8r%r&r'r(r)rs r<r3r3sZ"E!EJ=L%#(  #'    -$4y$ 7" *4=;tX>!2 !& !#  r=)rZrGrKz str | None) r;rGrpzAudioProto | VideoProtor6rrqrGrKNone)rLrNNFFFr$)r0rr;rGrprBr6rrqrGr8rr?rr&rHr'rJr(rJr@rJr)rrKr)r8rr&rIrKztuple[int, int | None])r6rrKztuple[bytes, int])r6rr%rrKr`)r6rr%rHrKr)rFrNNFFr$)r0rr;rGrpr.r6rrqrGr8rr%rHr&rHr'rJr(rJr)rrKr)E __future__rrarWdatetimerpathlibrrrrrr r streamlitr r r #streamlit.elements.lib.layout_utilsrr%streamlit.elements.lib.subtitle_utilsrstreamlit.elements.lib.utilsrstreamlit.errorsrstreamlit.proto.Audio_pb2rr.streamlit.proto.Video_pb2rrBstreamlit.proto.WidthConfig_pb2rstreamlit.runtimerstreamlit.runtime.metrics_utilrstreamlit.time_utilrrrnptstreamlit.delta_generatorrrGr`rbrerfr__annotations__rrrrrr r"rRr\rurCr-rrrr3rQr=r<rs# ??22SGH2997%9/#8 JJLL   9 $J#d3d U0BRZZ0O+O&PPSWW iU{Y.4 94EuR,R,p n En844 "4 4 4  4x "!*W W W  W   W  W  W W W  W W  W  W  W t  %5  :.(b, "!*S S S  S   S  S  S S S  S S  S  S r=