
    ;3h2U                       d Z ddlmZ ddlZddlZddlZddlmZmZ ddl	m
Z
 ddlmZmZmZ ddlZddlZddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZ ddlmZm Z m!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ erddl,m-Z-  e       ej\                   G d d                    Z/ e        G d de e!e             Z0y)zgr.Audio() component.    )annotationsN)CallableSequence)Path)TYPE_CHECKINGAnyLiteralhandle_file)utils)document)AudioSegment)processing_utilsr   
wasm_utils)	ComponentStreamingInputStreamingOutput)FileDataFileDataDictMediaStreamChunk)Events)Error)I18nData)Timerc                  t    e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   d
Z	ded<   dZ
ded<   dZded<   y)WaveformOptionsa  
    A dataclass for specifying options for the waveform display in the Audio component. An instance of this class can be passed into the `waveform_options` parameter of `gr.Audio`.
    Parameters:
        waveform_color: The color (as a hex string or valid CSS color) of the full waveform representing the amplitude of the audio. Defaults to a light gray color.
        waveform_progress_color: The color (as a hex string or valid CSS color) that the waveform fills with to as the audio plays. Defaults to the accent color.
        trim_region_color: The color (as a hex string or valid CSS color) of the trim region. Defaults to the accent color.
        show_recording_waveform: If True, shows a waveform when recording audio or playing audio. If False, uses the default browser audio players. For streamed audio, the default browser audio player is always used.
        show_controls: Deprecated and has no effect. Use `show_recording_waveform` instead.
        skip_length: The percentage (between 0 and 100) of the audio to skip when clicking on the skip forward / skip backward buttons.
        sample_rate: The output sample rate (in Hz) of the audio after editing.
    N
str | Nonewaveform_colorwaveform_progress_colortrim_region_colorTboolshow_recording_waveformFshow_controls   zint | floatskip_lengthiD  intsample_rate)__name__
__module____qualname____doc__r   __annotations__r   r    r"   r#   r%   r'        W/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/components/audio.pyr   r      sR    
 "&NJ%*.Z.$(z($(T(M4 K Kr.   r   c                  v    e Zd ZdZej
                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  gZeZ	 ddddddddddddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Zdd
ZddZ	 	 	 	 ddZ	 	 	 	 ddZedd       Zedd       Z	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZ	 	 	 	 ddZd Z xZS )Audioz
    Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
    Demos: generate_tone, reverse_audio
    Guides: real-time-speech-recognition
    NnumpyT   Fvalue)sourcestypelabeleveryinputs
show_label	containerscale	min_widthinteractivevisible	streamingelem_idelem_classesrenderkeypreserved_by_keyformatautoplayshow_download_buttonshow_share_buttoneditable
min_length
max_lengthwaveform_optionsloop	recordingc               6   ddg}||rdgn|| _         nCt        |t              r||v r	|g| _         n&t        |t              r|| _         nt	        d|       | j                   D ]  }||vst	        d|        ddg}||vr t	        d| d	d
j                  |             || _        || _        | j                  rd| j                   vrt	        d      ddg} |2|j                         | vr t	        d| d	d
j                  |              |xr |j                         | _	        || _
        || _        || _        |t        j                         dun|| _        || _        |t#               | _        n(t        |t&              rt#        di || _        n|| _        | j$                  j(                  durt+        j,                  d       || _        || _        || _        t4        !| m  ||||||	|
||||||||       | j                  dk(  rd| _        yd| _        y)at  
        Parameters:
            value: A path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio data as a float or int numpy array) for the default value that Audio component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.
            sources: A list of sources permitted for audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input. The first element in the list will be used as the default source. If None, defaults to ["upload", "microphone"], or ["microphone"] if `streaming` is True.
            type: The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio.
            label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
            every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
            inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
            show_label: if True, will display label.
            container: If True, will place the component in a container - providing some extra padding around the border.
            scale: Relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
            min_width: Minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
            interactive: If True, will allow users to upload and edit an audio file. If False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output.
            visible: If False, component will be hidden.
            streaming: If set to True when used in a `live` interface as an input, will automatically stream webcam feed. When used set as an output, takes audio chunks yield from the backend and combines them into one streaming audio output.
            elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
            elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
            render: if False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
            key: in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.
            preserved_by_key: A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
            format: the file extension with which to save audio files. Either 'wav' or 'mp3'. wav files are lossless but will tend to be larger files. mp3 files tend to be smaller. This parameter applies both when this component is used as an input (and `type` is "filepath") to determine which file format to convert user-provided audio to, and when this component is used as an output to determine the format of audio returned to the user. If None, no file format conversion is done and the audio is kept as is. In the case where output audio is returned from the prediction function as numpy array and no `format` is provided, it will be returned as a "wav" file.
            autoplay: Whether to automatically play the audio when the component is used as an output. Note: browsers will not autoplay audio files if the user has not interacted with the page yet.
            show_download_button: If True, will show a download button in the corner of the component for saving audio. If False, icon does not appear. By default, it will be True for output components and False for input components.
            show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
            editable: If True, allows users to manipulate the audio file if the component is interactive. Defaults to True.
            min_length: The minimum length of audio (in seconds) that the user can pass into the prediction function. If None, there is no minimum length.
            max_length: The maximum length of audio (in seconds) that the user can pass into the prediction function. If None, there is no maximum length.
            waveform_options: A dictionary of options for the waveform display. Options include: waveform_color (str), waveform_progress_color (str), show_controls (bool), skip_length (int), trim_region_color (str). Default is None, which uses the default values for these options. [See `gr.WaveformOptions` docs](#waveform-options).
            loop: If True, the audio will loop when it reaches the end and continue playing from the beginning.
            recording: If True, the audio component will be set to record audio from the microphone if the source is set to "microphone". Defaults to False.
        upload
microphoneNz3`sources` must be a list consisting of elements in z0`sources` must a list consisting of elements in r2   filepathz$Invalid value for parameter `type`: z. Please choose from one of:  z@Audio streaming only available if sources includes 'microphone'.wavmp3z&Invalid value for parameter `format`: Fz{The `show_controls` parameter is deprecated and will be removed in a future release. Use `show_recording_waveform` instead.)r7   r8   r9   r:   r;   r<   r=   r>   r?   rA   rB   rC   rD   rE   r4   za filepath to an audio filez=a tuple of [sample_rate: int, data: np.ndarray] of audio datar-   )r5   
isinstancestrlist
ValueErrorjoinr6   r@   lowerrF   rG   rN   rH   r   	get_spacerI   rJ   r   rM   dictr#   warningswarnrK   rL   rO   super__init___value_description)"selfr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   valid_sourcessourcevalid_typesvalid_formats	__class__s"                                    r/   rb   zAudio.__init__T   s   B AI,?W?-6L>MDL%']*B#9DL&"DLEm_U  ll 	F]* F}oV 	
 
+{"6tf<YZ]ZbZbcnZoYpq  	">>l$,,>R  &,,."E8@]^a^f^fgt^u]vw  / 	$8! !( __d*" 	
 !#$3$5D!($/$3$G6F$GD!$4D!  ..e;MM N %$"!#%- 	 	
& yyJ& * 	 Q 	r.   c                    t        d      S NzNhttps://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wavr
   rd   s    r/   example_payloadzAudio.example_payload   s    \
 	
r.   c                     yrk   r-   rl   s    r/   example_valuezAudio.example_value   s    _r.   c                2   ||S |j                   st        d      d}t        |j                         j                  j	                         }| j
                  |d| j
                   k7  rd}| j                  | j                  t        j                  |j                         \  }}t        |      |z  }| j                  (|| j                  k  rt        d| j                   d      | j                  (|| j                  kD  rt        d| j                   d      | j                  dk(  rt        j                  |j                         S | j                  d	k(  r|s|j                   S t        j                  |j                         \  }}t        t        |j                         j                  d| j
                               }| j
                  J t        j                  |||| j
                  
       |S t        dt        | j                        z   dz         )a  
        Parameters:
            payload: audio data as a FileData object, or None.
        Returns:
            passes audio as one of these formats (depending on `type`): a `str` filepath, or `tuple` of (sample rate in Hz, audio data as numpy array). If the latter, the audio data is a 16-bit `int` array whose values range from -32768 to 32767 and shape of the audio data array is (samples,) for mono audio or (samples, channels) for multi-channel audio.
        zpayload path missingF.Tz)Audio is too short, and must be at least z secondsz'Audio is too long, and must be at most r2   rS   rF   zUnknown type: z*. Please choose from: 'numpy', 'filepath'.)pathrZ   r   suffixr\   rF   rK   rL   r   audio_from_filelenr   r6   rX   with_suffixaudio_to_file)rd   payloadneeds_conversionoriginal_suffixr'   datadurationoutput_files           r/   
preprocesszAudio.preprocess   s    ?N||344 w||,3399;;;"Adkk]:K'K#??&$//*E 0 @ @ NK4y;.H*x$///I??PPXY  *x$///I=doo=NhW  99#33GLLAAYY*$#||# 0 @ @ NKd7<<0<<q=NOPK;;*****T;t{{  dii.!>? r.   c                0   d}|yt        |t              rG| j                  r|S t        j                  |d| j
                        }t        |      j                  }nt        |t              rM|\  }}t        j                  ||| j                  xs d| j
                        }t        |      j                  }nQt        |t        t        f      r+t        j                  |      rJt        t        j                  t        |            j                         j"                  j%                         }n#t        |      j"                  j%                         }| j                  a|d| j                   k7  rOt        j&                  t        |            \  }}t        j                  ||| j                  | j
                        }nt        |      }t        |      j)                         rt        |      j                  nd}nt+        d| d      t-        ||	      S )
a  
        Parameters:
            value: expects audio data in any of these formats: a `str` or `pathlib.Path` filepath or URL to an audio file, or a `bytes` object (recommended for streaming), or a `tuple` of (sample rate in Hz, audio data as numpy array). Note: if audio is supplied as a numpy array, the audio will be normalized by its peak value to avoid distortion or clipping in the resulting audio.
        Returns:
            FileData object, bytes, or None.
        Naudio	cache_dirrU   )rF   r   rq   zCannot process z	 as Audio)rs   	orig_name)rW   bytesr@   r   save_bytes_to_cacheGRADIO_CACHEr   nametuplesave_audio_to_cacherF   rX   client_utilsis_http_url_likehttpxURLrs   rt   r\   ru   existsrZ   r   )rd   r4   r   	file_pathr'   r|   r{   s          r/   postprocesszAudio.postprocess  s    	=eU#~~(<<w$*;*;I Y,,Iu% %K(<<{{+e++	I Y,,IT{+,,U3"&uyyU'<'A'A"B"I"I"O"O"Q"&u+"4"4":":"<{{&?$++>O+O$4$D$DSZ$P!T,@@+dkkTEVEV	  J	04Y0F0F0HY,,dIugY?@@Y)<<r.   c                *   t         j                  rt        j                  d      t        j                  t        j                  |             }t        j                         }|j                  |d       |j                         }|t        |      dz  fS )Nz2Audio streaming is not supported in the Wasm mode.adtsrr   g     @@)
r   IS_WASMWasmUnsupportedErrorr   	from_fileioBytesIOexportgetvaluerv   )r|   segmentbufferaac_datas       r/   _convert_to_adtszAudio._convert_to_adtsL  sw    11D  ((D)9:vf-??$W...r.   c                z   K   t         j                  j                  t        j                  |        d {   S 7 wN)anyio	to_threadrun_syncr1   r   )r|   s    r/   covert_to_adtszAudio.covert_to_adtsY  s)     __--e.D.DdKKKKs   2;9;c                  K   |ddddid}|d |fS t        |t              r$| j                  |       d {   \  }}||dd|fS t        j                  |d         r%t        j                  |d         }|j                  }n2|d	   |d	<   |d   }t        |d
      5 }	|	j                         }d d d        | j                         d {   \  }}||dd|fS 7 # 1 sw Y   /xY w7 w)NTaudio-stream.mp3_typezgradio.FileData)rs   	is_streamr   metaz.aac)r|   r}   	extensionrs   r   rb)
rW   r   r   r   r   r   getcontentopenread)
rd   r4   	output_idfirst_chunkr~   r}   responsebinary_datar   fs
             r/   stream_outputzAudio.stream_output]  s     +/0	%
 =$$eU#$($7$7$>>OE8$# 	 
 ((v7yyv/H"**K',['9K$fIi& '!ffh' $ 3 3K @@x8&I;VV ?' '@s4   4C)CA%C)C-C)	C'
C)C$ C)c                d  K   t        t        j                  dj                  |      d| j                        dd      }|rl|dk7  rgt        |j                        j                  d|       }t        j                  |j                        j                  ||	       t        |      |_        |S w)
Nr.   z	audio.mp3r   Fr   )rs   r   r   rV   rq   rr   )r   r   r   r[   r   r   rs   rw   r   r   r   rX   )rd   streamdesired_output_format	only_filer~   new_paths         r/   combine_streamzAudio.combine_stream}  s      !55 +9J9J (
 !%:e%CK,,-99A>S=T:UVH"";#3#34;;!6 <   #8}Ks   B.B0c                `    |yt        |t        t        f      rt        |      j                  S y)N z(audio))rW   rX   r   r   )rd   r4   s     r/   process_examplezAudio.process_example  s-     =T{+;###r.   c                j    | j                   'd| j                   vr| j                  rt        d      y y y )NrR   z?Audio streaming only available if source includes 'microphone'.)r5   r@   rZ   rl   s    r/   check_streamablezAudio.check_streamable  s>    LL$DLL0Q   1 %r.   r   )8r4   z5str | Path | tuple[int, np.ndarray] | Callable | Noner5   zNlist[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | Noner6   zLiteral['numpy', 'filepath']r7   zstr | I18nData | Noner8   zTimer | float | Noner9   z7Component | Sequence[Component] | set[Component] | Noner:   bool | Noner;   r!   r<   
int | Noner=   r&   r>   r   r?   r!   r@   r!   rA   r   rB   list[str] | str | NonerC   r!   rD   z(int | str | tuple[int | str, ...] | NonerE   r   rF   zLiteral['wav', 'mp3'] | NonerG   r!   rH   r   rI   r   rJ   r!   rK   r   rL   r   rM   zWaveformOptions | dict | NonerN   r!   rO   r!   )returnr   )ry   zFileData | Noner   z#str | tuple[int, np.ndarray] | None)r4   z2str | Path | bytes | tuple[int, np.ndarray] | Noner   zFileData | bytes | None)r|   r   )r|   r   r   ztuple[bytes, float])r   rX   r   r!   r   z,tuple[MediaStreamChunk | None, FileDataDict])NF)r   zlist[bytes]r   r   r   r   )r4   z2tuple[int, np.ndarray] | str | Path | bytes | Noner   rX   ) r(   r)   r*   r+   r   r   changeclearplaypausestopstart_recordingpause_recordingstop_recordingrQ   inputEVENTSr   
data_modelrb   rm   ro   r   r   staticmethodr   r   r   r   r   r   __classcell__)ri   s   @r/   r1   r1   7   s    	F J HLM
 -4'+&*JN"& #'"/38<3:/3,0)-!%!%:>AM
DM
	M
 +M
 %M
 $M
 HM
  M
 M
 M
 M
 !M
  !M
" #M
$ %M
& -'M
( )M
* 6+M
, 1-M
. -/M
0 1M
2 *3M
4 '5M
6 7M
8 9M
: ;M
< 8=M
> ?M
@ AM
^

`1&1	,1f,=G,=	 ,=\ 
/ 
/ L LW W 	W
 
6WF -1	  *
 
*G	r.   r1   )1r+   
__future__r   dataclassesr   r_   collections.abcr   r   pathlibr   typingr   r   r	   r   r   r2   npgradio_clientr   r   r   gradio_client.documentationr   pydubr   gradior   r   gradio.components.baser   r   r   gradio.data_classesr   r   r   gradio.eventsr   gradio.exceptionsr   gradio.i18nr   gradio.componentsr   	dataclassr   r1   r-   r.   r/   <module>r      s     "  	  .  . .    % / 0  6 6 M M H H   #  ' 
   , 
kk kr.   