
    8P[iZ                       d Z ddlm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 ddlmZmZmZ ddl 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_utils)	ComponentStreamingInputStreamingOutput)Button)FileDataFileDataDictMediaStreamChunk)Events)I18nData)set_default_buttons)Timerc                  f    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<   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.
        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_waveform   zint | floatskip_lengthiD  intsample_rate)__name__
__module____qualname____doc__r   __annotations__r    r!   r#   r%   r'        e/var/www/html/chatbot/Makanify-Chatbot-2/venv/lib/python3.12/site-packages/gradio/components/audio.pyr   r      sH    	 "&NJ%*.Z.$(z($(T( K Kr.   r   c                      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 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"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valuer   )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editablebuttonswaveform_optionsloop	recording	subtitlesplayback_positionc               *   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        |ddg      | _        || _        |t               | _        n(t        |t"              rt        di || _        n|| _        || _        || _        t(         | U  ||||||	|
||||||||       | j                  dk(  rdnd| _        d| _        |>t        |t              r| j1                  |      | _        y| j3                  |      | _        yy)a  
        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. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM.
            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 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.
            buttons: A list of buttons to show in the top right corner of the component. Valid options are "download", "share", or a gr.Button() instance. The "download" button allows the user to save the audio to their device. The "share" button allows the user to share the audio via Hugging Face Spaces Discussions. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, only the "download" and "share" buttons are shown.
            editable: If True, allows users to manipulate the audio file if the component is interactive. Defaults to True.
            waveform_options: A dictionary of options for the waveform display. Options include: waveform_color (str), waveform_progress_color (str), 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.
            subtitles: A subtitle file (srt, vtt, or json) for the audio, or a list of subtitle dictionaries in the format [{"text": str, "timestamp": [start, end]}] where timestamps are in seconds. JSON files should contain an array of subtitle objects.
            playback_position: The starting playback position in seconds. This value is also updated as the audio plays, reflecting the current playback position.
        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`: downloadshare)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   rK   r   rI   rH   r   rJ   dictrL   rN   super__init___value_descriptionrM   _process_json_subtitles_process_subtitle_file)!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   valid_sourcessourcevalid_typesvalid_formats	__class__s!                                   r/   r`   zAudio.__init__R   su   ~ 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  / 	*7Z4IJ #$3$5D!($/$3$G6F$GD!$4D!"!2!#%- 	 	
& yyJ& *P 	
  )T*!%!=!=i!H!%!<!<Y!G	 !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                   ||S |j                   st        d      d}t        |j                         j                  j	                         }| j
                  |d| j
                   k7  r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.Tr2   rR   rF   zUnknown type: z*. Please choose from: 'numpy', 'filepath'.)pathr[   r   suffixr]   rF   r6   r   audio_from_filerY   with_suffixaudio_to_file)rd   payloadneeds_conversionoriginal_suffixr'   dataoutput_files          r/   
preprocesszAudio.preprocess   s=    ?N||344 w||,3399;;;"Adkk]:K'K#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_dirrT   )rF   r   rq   zCannot process z	 as Audio)rs   	orig_name)rX   bytesr@   r   save_bytes_to_cacheGRADIO_CACHEr   nametuplesave_audio_to_cacherF   rY   client_utilsis_http_url_likehttpxURLrs   rt   r]   ru   existsr[   r   )rd   r4   r   	file_pathr'   r{   rz   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                  t        j                  |             }t        j                         }|j	                  |d       |j                         }|t        |      dz  fS )Nadtsrr   g     @@)r   	from_fileioBytesIOexportgetvaluelen)r{   segmentbufferaac_datas       r/   _convert_to_adtszAudio._convert_to_adts7  sV    ((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_adts@  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{   duration	extensionrs   r   rb)
rX   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_outputD  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   rU   rq   rr   )r   r   r   r\   r   r   rs   rv   r   r   r   rY   )rd   streamdesired_output_format	only_filer|   new_paths         r/   combine_streamzAudio.combine_streamd  s      !55 +9J9J (
 !%:e%CK,,-99A>S=T:UVH"";#3#34;;!6 <   #8}Ks   B.B0c                t   t        |      D ]  \  }}t        |t              st        d| d      d|vrt        d| d      d|vrt        d| d      t        |d   t        t
        f      rt        |d         dk7  svt        d| d       |D cg c]  }|d   d	   |d   d
   |d   d c}S c c}w )NzSubtitle at index z must be a dictionarytextz missing required 'text' field	timestampz# missing required 'timestamp' field   z1 'timestamp' must be a list/tuple of [start, end]r      )startendr   )	enumeraterX   r^   r[   rZ   r   r   )rd   rM   isubtitles       r/   rb   zAudio._process_json_subtitlesy  s    %Y/ 	KAxh- #5aS8M!NOOX% #5aS8V!WXX(* (+NO  x4tUmDx,-2 (+\] 	, &
 	 "+.q1,Q/ (
 	
 
s   B5c                   dd l }ddlm}  ||      }|j                  j	                         dk(  rU	 t        |d      5 }|j                  |      }d d d        t        t              r| j                  |      S t        d      d t        |      S # 1 sw Y   AxY w# |j                  $ r}t        d|       |d }~wt        $ r}t        d|       |d }~ww xY w)	Nr   r   z.jsonzutf-8)encodingz:JSON subtitle file must contain a list of subtitle objectsz&Invalid JSON format in subtitle file: z"Error reading JSON subtitle file: )jsonpathlibr   rt   r]   r   loadrX   rZ   rb   r[   JSONDecodeError	Exceptionr   )rd   subtitle_filer   r   r   r   	json_dataes           r/   rc   zAudio._process_subtitle_file  s     	 '	!!#w.R)g6 -! $		!I-i.77	BB$T  =))- - '' V #I!!MNTUU R #EaS!IJPQQRs@   B B(B 9B BB C+B::CCCc                `    |yt        |t        t        f      rt        |      j                  S y)N z(audio))rX   rY   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 )NrQ   z?Audio streaming only available if source includes 'microphone'.)r5   r@   r[   rl   s    r/   check_streamablezAudio.check_streamable  s>    LL$DLL0Q   1 %r.   r   )6r4   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<   z
int | Noner=   r&   r>   r   r?   zbool | Literal['hidden']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   z2list[Literal['download', 'share'] | Button] | NonerJ   zWaveformOptions | dict | NonerK   r"   rL   r"   rM   z(str | Path | list[dict[str, Any]] | NonerN   float)returnr	   )rx   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   rY   r   r"   r   z,tuple[MediaStreamChunk | None, FileDataDict])NF)r   zlist[bytes]r   r   r   r   )rM   list[dict[str, Any]]r   r   )r   z
str | Pathr   zFileData | list[dict[str, Any]])r4   z2tuple[int, np.ndarray] | str | Path | bytes | Noner   rY   )"r(   r)   r*   r+   r   r   changeclearplaypausestopstart_recordingpause_recordingstop_recordingrP   inputEVENTSr   
data_modelr`   rm   ro   r}   r   staticmethodr   r   r   r   rb   rc   r   r   __classcell__)ri   s   @r/   r1   r1   5   s    	F J HLGH -4'+&*JN"& #',0"/38<3:/3FJ:>>B#$?GHDGH	GH +GH %GH $GH HGH  GH GH GH GH !GH  *!GH" #GH$ %GH& -'GH( )GH* 6+GH, 1-GH. -/GH0 1GH2 3GH4 D5GH6 87GH8 9GH: ;GH< <=GH> !?GHR

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