o
    eP                  	   @  sD  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZmZmZmZmZmZ ddlmZ ddlZddlZddlZddlmZ ddlm Z m!Z! ddl"m#Z# dd	l$m%Z%m&Z&m'Z'm(Z(mZ dd
l)m*Z* ddl+m,Z, ddl-m.Z. erddl/m0Z0 ddl1m2Z2 dZ3dZ4e!d 												dndod+d,Z5e  G d-d. d.Z6dpd4d5Z7G d6d7 d7Z8e d8d9G d:d; d;eZ9d<d= Z:			dqdrdDdEZ;e  dsdHdIZ<dsdJdKZ=e  dLddMdNdOdPddQdtd^d_Z>e  G d`da daZ?dudvdfdgZ@e  dwdxdidjZAe  dydxdldmZBdS )zzK
Defines helper methods useful for loading and caching Interface examples.
    )annotationsN)Path)TYPE_CHECKINGAnyCallableIterableLiteralOptional)utils)documentset_documentation_group)	animation)
componentsoauthprocessing_utilsroutesr
   )Context)Error)	CSVLogger)Block)IOComponentZgradio_cached_exampleslog.csvhelpersF
   Texamples!list[Any] | list[list[Any]] | strinputsIOComponent | list[IOComponent]outputs&IOComponent | list[IOComponent] | NonefnCallable | Nonecache_examplesboolexamples_per_pageint	_api_modelabel
str | Noneelem_idrun_on_click
preprocesspostprocessapi_namestr | None | Literal[False]batchc                 C  s6   t | |||||||||	|
|||dd}t|j |S )zTop-level synchronous function that creates Examples. Provided for backwards compatibility, i.e. so that gr.Examples(...) can be used to create the Examples component.F)r   r   r   r    r"   r$   r&   r'   r)   r*   r+   r,   r-   r/   _initiated_directly)Examplesclient_utilsZsynchronize_asynccreate)r   r   r   r    r"   r$   r&   r'   r)   r*   r+   r,   r-   r/   Zexamples_obj r4   >D:\Projects\ConvertPro\env\Lib\site-packages\gradio/helpers.pycreate_examples)   s&   r6   c                   @  sT   e Zd ZdZ						 							d)d*ddZd+d!d"Zd+d#d$Zd,d'd(ZdS )-r1   aQ  
    This class is a wrapper over the Dataset component and can be used to create Examples
    for Blocks / Interfaces. Populates the Dataset component with examples and
    assigns event listener so that clicking on an example populates the input/output
    components. Optionally handles example caching for fast inference.

    Demos: blocks_inputs, fake_gan
    Guides: more-on-examples-and-flagging, using-hugging-face-integrations, image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, create-your-own-friends-with-a-gan
    NFr   Tr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   c              
     sb  |rt d |r|du s|du rtdttsg|r't|ts'|g}t  } du r4tdt trGt dksFt d trGnyt trZtdkrZdd  D  nft trt 	 slt
d	   }t t 	 stdkrd
d t D  n9t
dt tt t }tt|  fddtdt D  W d   n1 sw   Y  ntddgt  D ]}t|D ]\}}|durzd|< W q ty   Y qw qqdd tD }fdd D } | _|| _| _|| _|pg | _|| _|| _|| _|| _|| _|| _|| _ t!"| fdd D | _#W d   n	1 s>w   Y  fdd| j#D | _$|rn| jD ]}tdd |D t| jkrlt d  nqTddl%m&} t!"| |j'||d|||	d| _(W d   n	1 sw   Y  tt)t| j(j* | _+t| j+d | _,|| _|
| _-dS )a'
  
        Parameters:
            examples: example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.
            inputs: the component or list of components corresponding to the examples
            outputs: optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache` is True.
            fn: optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache` is True.
            cache_examples: if True, caches examples for fast runtime. If True, then `fn` and `outputs` must be provided. If `fn` is a generator function, then the last yielded value will be used as the output.
            examples_per_page: how many examples to show per page.
            label: the label to use for the examples component (by default, "Examples")
            elem_id: an optional string that is assigned as the id of this component in the HTML DOM.
            run_on_click: if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True.
            preprocess: if True, preprocesses the example input before running the prediction function and caching the output. Only applies if cache_examples is True.
            postprocess: if True, postprocesses the example output after running the prediction function and before caching. Only applies if cache_examples is True.
            api_name: Defines how the event associated with clicking on the examples appears in the API docs. Can be a string, None, or False. If False (default), the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
            batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. Used only if cache_examples is True.
        zXPlease use gr.Examples(...) instead of gr.examples.Examples(...) to create the Examples.Nz8If caching examples, `fn` and `outputs` must be providedz'The parameter `examples` cannot be Noner      c                 S     g | ]}|gqS r4   r4   .0er4   r4   r5   
<listcomp>       z%Examples.__init__.<locals>.<listcomp>z#Could not find examples directory: c                 S  r8   r4   r4   r9   r4   r4   r5   r<      r=   z8Could not find log file (required for multiple inputs): c                   s    g | ]} | d t  qS N)lenr:   i)r   r   r4   r5   r<      s    zThe parameter `examples` must either be a string directory or a list(if there is only 1 input component) or (more generally), a nested list, where each sublist represents a set of inputs.FTc                 S     g | ]\}}|r|qS r4   r4   )r:   inpkeepr4   r4   r5   r<      s
    c                       g | ]}d d t | D qS )c                 S  rB   r4   r4   r:   exrD   r4   r4   r5   r<          0Examples.__init__.<locals>.<listcomp>.<listcomp>zipr:   exampleinput_has_examplesr4   r5   r<          c                   s    g | ]}d d t  |D qS )c                 S  s   g | ]	\}}| |qS r4   )r,   )r:   	componentsampler4   r4   r5   r<      s    rI   rJ   rL   )r   r4   r5   r<      s    c                   rE   )c                 S  rB   r4   r4   rF   r4   r4   r5   r<      rH   rI   rJ   rL   rN   r4   r5   r<      rP   c                 S  s   g | ]}|d ur|qS r>   r4   )r:   rG   r4   r4   r5   r<      rH   aS  Examples are being cached but not all input components have example values. This may result in an exception being thrown by your function. If you do get an error while caching examples, make sure all of your inputs have example values for all of your examples or you provide default values for those particular parameters in your function.)r   index)r   samplestyper'   Zsamples_per_pager)   r   ).warningswarn
ValueError
isinstancelistr   absoluter?   strexistsFileNotFoundErrorLOG_FILEoslistdiropencsvreaderrange	enumerate
IndexErrorrK   r   non_none_examplesr   inputs_with_examplesr   r    r"   r&   r+   r,   r-   r/   r
   Zset_directoryprocessed_examplesnon_none_processed_examplesgradior   ZDatasetdatasetCACHED_FOLDERZ_idcached_foldercached_filer*   )selfr   r   r   r    r"   r$   r&   r'   r)   r*   r+   r,   r-   r/   r0   Zworking_directoryZlogsrM   idxZexample_for_inputri   rh   r   r4   )r   rO   r   r5   __init__[   s   "












zExamples.__init__returnNonec              	     s    fdd}t jr7 jj| jg jddd jd _ jr7 js7 j	du r+t
d jj j	 j jd  jrC  I dH  dS dS )	zqCaches the examples if self.cache_examples is True and creates the Dataset
        component to hold the examplesc                   s    j |  }t|S r>   )rk   r
   resolve_singleton
example_idZprocessed_examplerq   r4   r5   load_example   s   

z%Examples.create.<locals>.load_examplehiddenFr   r   show_progressr,   queuer-   Nz.Cannot run_on_click if no function is provided)r   r   )r   
root_blockrm   clickri   r-   load_input_eventr*   r"   r    rX   Zthenr   r   cache)rq   rz   r4   ry   r5   r3      s.   	
zExamples.createc              	     sT  t j rtdtj d dS tjdu rt	dtdtj d t
 }g  tjr@ fdd}|}ntjrP fd	d}|}nj}tjjd
|jjjobj johj jd\}}jdusvJ |jj tjD ]a\}}td|d  dtj  j| }jrdd |D }t  tjj||di dI dH }	W d   n1 sw   Y  |	d }
t rtj |
}
jrdd |
D }
||
 qtjj | tjj!"| tjj#j$}tjj"| tjj!"| fdd}j%j&|j%gjj dddj'd_$td dS )z`
        Caches all of the examples so that their predictions can be shown immediately.
        zUsing cache from 'zg' directory. If method or examples have changed since last caching, delete this folder to clear cache.
Nz0Cannot cache examples if not in a Blocks contextzCaching examples at: ''c                    s*   d }    j|  D ]} | q|S r>   clearr    appendargsxgenerated_valuesrq   r4   r5   get_final_item)  s
   z&Examples.cache.<locals>.get_final_itemc                    s6   d }    j|  2 z3 d H W } | q6 |S r>   r   r   r   r4   r5   r   3  s   Z
fake_event)Z
event_namer    r   r   r+   r,   r/   zCaching example r7   /c                 S  r8   r4   r4   r:   valuer4   r4   r5   r<   O  r=   z"Examples.cache.<locals>.<listcomp>)fn_indexr   requeststatedatac                 S  s   g | ]}|d  qS )r   r4   r   r4   r4   r5   r<   ^  s    c                   s&    j |   | I d H  }t|S r>   )rk   load_from_cacher
   rv   rw   ry   r4   r5   rz   k  s   
z$Examples.cache.<locals>.load_exampler{   Fr|   zCaching complete
)(r   rp   r]   printr
   abspathro   r   r   rX   r   inspectisgeneratorfunctionr    isasyncgenfunctionZset_event_triggerri   r   r+   r&   r,   r/   setuprf   r   r?   rj   MatplotlibBackendManangerZprocess_api"merge_generated_values_into_outputflagdependenciesremovefnspoprS   r   rm   r   r-   )rq   Zcache_loggerr   r    
dependencyr   rx   _Zprocessed_inputZ
predictionoutputrS   rz   r4   r   r5   r     s   






zExamples.cacherx   	list[Any]c           
        s   t | jdd}tt|}W d   n1 sw   Y  ||d  }g }| jdus.J t| j|D ]?\}}|}z t|}	t	|	trMt	|t
jrM|	}t|	sTJ ||	 W q4 ttttfys   ||j|| jdd Y q4w |S )zLoads a particular cached example for the interface.
        Parameters:
            example_id: The id of the example to process (zero-indexed).
        zutf-8)encodingNr7   T)Zallow_links)rb   rp   rZ   rc   rd   r   rK   astliteral_evalrY   r   Filer
   Z	is_updater   rX   	TypeErrorSyntaxErrorAssertionError	serializero   )
rq   rx   r   r   rM   r   rQ   r   Zvalue_to_useZvalue_as_dictr4   r4   r5   r   }  s2   
zExamples.load_from_cache)NNFr   Fr1   NFTTFFT)r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r#   r'   r(   r)   r(   r*   r#   r+   r#   r,   r#   r-   r.   r/   r#   r0   r#   )rt   ru   )rx   r%   rt   r   )__name__
__module____qualname____doc__rs   r3   r   r   r4   r4   r4   r5   r1   O   s(     

fr1   r   list[IOComponent]r   rZ   r   c              
   C  s  ddl m} t| D ]{\}}t||r|jrg }t|D ]!\}}t| dkr*|| }||}	|||	d|dkd  qd	|}
t
jdpRttt d }t
j|dd	 tj|d
d}t|jd}||
 W d    n1 sww   Y  |jdd d||< q
|S )Nr   )StreamableOutputr7        ZGRADIO_TEMP_DIRrl   T)exist_okF)dirdeletewb)nameis_filer   )Zgradio.eventsr   rf   rY   Z	streamingr?   r,   r   Zstream_outputjoinr`   environgetr\   r   tempfile
gettempdirmakedirsNamedTemporaryFilerb   r   write)r   r   r   r   Zoutput_indexZoutput_componentZbinary_chunksrA   chunkZprocessed_chunkZbinary_datatempdir	temp_filefr4   r4   r5   r     s:   


r   c                   @  s   e Zd Z		ddddZdS )TrackedIterableNiterableIterable | NonerS   
int | Nonelengthdescr(   unitprogressfloat | Nonert   ru   c                 C  s.   || _ || _|| _|| _|| _|| _|| _d S r>   )r   rS   r   r   r   _tqdmr   )rq   r   rS   r   r   r   r   r   r4   r4   r5   rs     s   

zTrackedIterable.__init__)NN)r   r   rS   r   r   r   r   r(   r   r(   r   r   rt   ru   )r   r   r   rs   r4   r4   r4   r5   r     s    r   __call__tqdmc                   @  st   e Zd ZdZ			d%d&d
dZdd Zdd Zdd Z				d'd(ddZ				d'd)ddZ	d*d!d"Z
d#d$ ZdS )+ProgressaX  
    The Progress class provides a custom progress tracker that is used in a function signature.
    To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a `gradio.Progress()` instance.
    The Progress tracker can then be updated in the function by calling the Progress object or using the `tqdm` method on an Iterable.
    The Progress tracker is currently only available with `queue()`.
    Example:
        import gradio as gr
        import time
        def my_function(x, progress=gr.Progress()):
            progress(0, desc="Starting...")
            time.sleep(1)
            for i in progress.tqdm(range(100)):
                time.sleep(0.1)
            return x
        gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()
    Demos: progress
    FN
track_tqdmr#   	_callbackr!   	_event_idr(   c                 C  s   || _ || _|| _g | _dS )z
        Parameters:
            track_tqdm: If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function.
        N)r   r   r   	iterables)rq   r   r   r   r4   r4   r5   rs     s   

zProgress.__init__c                 C  s   | j d jS )N)r   r   ry   r4   r4   r5   __len__  s   zProgress.__len__c                 C  s   | S r>   r4   ry   r4   r4   r5   __iter__  s   zProgress.__iter__c                 C  s   | j rT| jd }t|jds't| jdkr'| j }t|jds't| jdks| j | j| jd |jdus9J d| jd7  _zt|jW S  t	yS   | j   w | S )zF
        Updates progress tracker with next item in iterable.
        r   __next__r   event_idr   NIndex not set.r7   )
r   r   hasattrr   r?   r   r   rS   nextStopIteration)rq   current_iterabler4   r4   r5   r     s,   




zProgress.__next__stepsr   %float | tuple[int, int | None] | Noner   totalr   r   r\   c                 C  sR   | j r't|tr|\}}d}nd}| j | j| jtd||||||g d dS |S )a  
        Updates progress tracker with progress and message text.
        Parameters:
            progress: If float, should be between 0 and 1 representing completion. If Tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar.
            desc: description to display.
            total: estimated total number of steps.
            unit: unit of iterations.
        Nr   )r   rY   tupler   r   r   )rq   r   r   r   r   r   rS   r4   r4   r5   r     s   

zProgress.__call__r   r   c              	   C  sz   | j r;|du r!tdd||||}| j| | j | j| jd | S t|dr*t|nd}| jtt|d|||| | S )a  
        Attaches progress tracker to iterable, like tqdm.
        Parameters:
            iterable: iterable to attach progress tracker to.
            desc: description to display.
            total: estimated total number of steps.
            unit: unit of iterations.
        Nr   r   r   )r   r   r   r   r   r   r?   iter)rq   r   r   r   r   r   Znew_iterabler   r4   r4   r5   r   5  s   zProgress.tqdmr7   c                 C  sX   | j r*t| jdkr*| jd }|jdusJ d| j|7  _| j | j| jd dS dS )z
        Increases latest iterable with specified number of steps.
        Parameters:
            n: number of steps completed.
        r   r   Nr   r   )r   r?   r   rS   r   )rq   nr   r4   r4   r5   updateQ  s   

zProgress.updatec                 C  s\   | j r,tt| jD ]}t| j| jt|kr | j|  nq
| j | j| jd dS dS )z4
        Removes iterable with given _tqdm.
        r   N)r   re   r?   r   idr   r   r   )rq   r   rA   r4   r4   r5   closeb  s   
zProgress.close)FNN)r   r#   r   r!   r   r(   )NNr   N)r   r   r   r(   r   r   r   r\   )r   r   r   r(   r   r   r   r\   r7   )r   r   r   r   rs   r   r   r   r   r   r   r   r4   r4   r4   r5   r     s*    !
r   c                   sz  t jj d|s|fS ztd}W n ty!   |f Y S w tds*i _	d fdd	}dd }dd
d}dd }dd }	t|jdsP|jj|j_	||j_t|jds`|jj
|j_||j_
t|jdsp|jj|j_||j_t|jds|jj|j_|	|j_t|jds|jj|j_||j_t|drt|jdr|j|j_fdd}
fdd}tj||
|d}|fS )N)r   r   r   _progress_tracker_per_threadr   c                   sn   j t | _| jd ur% | j_| jj||||| d ttj	d|d< | j
|||g|R d|i| d S )N)r   wfiler   )r   r   	threading	get_ident	_progressr   r   rb   r`   devnull__init__orig__)rq   r   r   r   r   r   kwargs)r   root_blocksr4   r5   	init_tqdm  s   
$z!create_tracker.<locals>.init_tqdmc                 S  s   | j d ur| j S |  S r>   )r   __iter__orig__ry   r4   r4   r5   	iter_tqdm  s   
z!create_tracker.<locals>.iter_tqdmr7   c                 S  s    | j d ur| j | | |S r>   )r   r   __update__orig__)rq   r   r4   r4   r5   update_tqdm  s   

z#create_tracker.<locals>.update_tqdmc                 S  s   | j d ur| j |  |  S r>   )r   r   __close__orig__ry   r4   r4   r5   
close_tqdm  s   
z"create_tracker.<locals>.close_tqdmc                 S  s$   | j d ur| j |  | |||S r>   )r   r   __exit__orig__)rq   exc_type	exc_value	tracebackr4   r4   r5   	exit_tqdm  s   
z!create_tracker.<locals>.exit_tqdmr   r   r   r   r   autoc                    s   t  }  j| < d S r>   r   r   r   	thread_id)r   r   r4   r5   	before_fn  s   z!create_tracker.<locals>.before_fnc                    s   t  }  j| = d S r>   r  r  )r   r4   r5   after_fn  s   z create_tracker.<locals>.after_fn)r  r	  )NNNr   r   )r   _queueZset_progress
__import__ModuleNotFoundErrorr   r   r   rs   r   r   r   r   r   __exit__r   r   r   r  r
   Zfunction_wrapper)r   r   r    r   r   r   r   r   r   r  r  r	  Z
tracked_fnr4   )r   r   r   r5   create_trackers  sJ   


r  r   list[Any] | Noner   routes.Request | None
event_dataEventData | Nonec                 C  s  t | }t| }g }|j D ]}|j|j|jfvr n|	| qd}d}	t
|D ]\}
}||j}t|jtrJ|
}|durI||
|j q,|tjkrZ|durY||
| q,|ttj ksf|tjkr|durt|di pytt|dddi }d|v r|d nd}|tjkr|du rtd||
| q,|rt |rt|tr|
}	|dur|dur||
||j|j q,|j|jur|durt||
kr||
|j q,|durt|t|k rt|}
||
 }|j|jkrt d |	d n|	|j t|t|k s|pg ||	fS )a  
    Checks if function has special arguments Request or EventData (via annotation) or Progress (via default value).
    If inputs is provided, these values will be loaded into the inputs array.
    Parameters:
        fn: function to check.
        inputs: array to load special arguments into.
        request: request to load into inputs.
        event_data: event-related data to load into inputs.
    Returns:
        updated inputs, progress index, event data index.
    Nsessionr   oauth_profilez@This action requires a logged in user. Please sign in and retry.z'Unexpected argument. Filling with None.)!r   	signaturer
   get_type_hints
parametersvalueskindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr   rf   r   r   rY   defaultr   insertr   Requestr	   r   ZOAuthProfilegetattrr   isclass
issubclass	EventDatatarget_dataemptyr?   rV   rW   )r    r   r   r  r  Z
type_hintsZpositional_argsparamZprogress_indexZevent_data_indexrA   Z	type_hintr  r  r4   r4   r5   special_args  sr   



 

r'  rt   dictc                  K  s   d| d< | S )a3  
    Updates component properties. When a function passed into a Gradio Interface or a Blocks events returns a typical value, it updates the value of the output component. But it is also possible to update the properties of an output component (such as the number of lines of a `Textbox` or the visibility of an `Image`) by returning the component's `update()` function, which takes as parameters any of the constructor parameters for that component.
    This is a shorthand for using the update method on a component.
    For example, rather than using gr.Number.update(...) you can just use gr.update(...).
    Note that your editor's autocompletion will suggest proper parameters
    if you use the update method on the component.
    Demos: blocks_essay, blocks_update, blocks_essay_update

    Parameters:
        kwargs: Key-word arguments used to update the component's properties.
    Example:
        # Blocks Example
        import gradio as gr
        with gr.Blocks() as demo:
            radio = gr.Radio([1, 2, 4], label="Set the value of the number")
            number = gr.Number(value=2, interactive=True)
            radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
        demo.launch()

        # Interface example
        import gradio as gr
        def change_textbox(choice):
          if choice == "short":
              return gr.Textbox.update(lines=2, visible=True)
          elif choice == "long":
              return gr.Textbox.update(lines=8, visible=True)
          else:
              return gr.Textbox.update(visible=False)
        gr.Interface(
          change_textbox,
          gr.Radio(
              ["short", "long", "none"], label="What kind of essay would you like to write?"
          ),
          gr.Textbox(lines=2),
          live=True,
        ).launch()
    Zgeneric_updateZ__type__r4   )r   r4   r4   r5   r     s   'r   c                   C  s   t  S r>   )r   r4   r4   r4   r5   skip=  s   r)  z#f3f4f6g      ?)z#fbbf24z#ea580c2   g333333?)bg_colorbg_imagefg_alpha
bars_color	bar_count	bar_widthanimateaudiostr | tuple[int, np.ndarray]r+  r\   r,  r-  floatr.  str | tuple[str, str]r/  r0  r1  c          #        s  t | tr| }t| } ntjddd}	tj| d | d |	jdd |	j}tj	
|s/tdtd	}
|
s:td
tt| d | d  d}dd fdd}| d tjdkrbtd|t|  }td|fgt|dfttdt ; t  t |tr|n	||d |d |}|rtjdddd}|jddddd td tjdd |r|nd}tj t!d|d d |||d tjddd}ddi}|durd|d< |rd |d!< n||d!< tj"|jfi | |st#j$%|j}|&d"}|durt'|}|ddddd#f | |ddddd#f< t#j$(|}t#j$%|}|j)\}}|j)\}}||kr`|&|dt*|| | d  f}|j)\}}t||}t#j$+d$||fd%}|,|d|| f |,|d|| f| |-|j |j)\}}n/|j)\}}|-|j n# fd&d'}t*|d( }t.j/||dd|d)d*} | j-|jd+d(d,|d- W d   n	1 sw   Y  tjd.dd}!|r|dur|
d/d0d1|d1|jd1|d2d3d4t|d5d6d5d7d8d9d:d;d<d=|!jg}"n<|r|du r|
d1|jd1|d2d>d5d?d5d@d8d9d:d;d<d=|!jg}"n|
d/d0d1|jd1|dAdB| dC| dD| dEd4t|d=|!jg}"t01|" |!jS )Fab  
    Generates a waveform video from an audio file. Useful for creating an easy to share audio visualization. The output should be passed into a `gr.Video` component.
    Parameters:
        audio: Audio file path or tuple of (sample_rate, audio_data)
        bg_color: Background color of waveform (ignored if bg_image is provided)
        bg_image: Background image of waveform
        fg_alpha: Opacity of foreground waveform
        bars_color: Color of waveform bars. Can be a single color or a tuple of (start_color, end_color) of gradient
        bar_count: Number of bars in waveform
        bar_width: Width of bars in waveform. 1 represents full width, 0.5 represents half width, etc.
        animate: If true, the audio waveform overlay will be animated, if false, it will be static.
    Returns:
        A filepath to the output video in mp4 format.
    z.wavF)suffixr   r   r7   Zwav)formatzAudio file not found.ffmpegzffmpeg not found.   c                   s    fddt dddD S )Nc                   s"   g | ]}t  ||d   dqS )      )r%   r@   hex_strr4   r5   r<   n  s   " z5make_waveform.<locals>.hex_to_rgb.<locals>.<listcomp>r7      r:  )re   r<  r4   r<  r5   
hex_to_rgbm  s   z!make_waveform.<locals>.hex_to_rgbc                   sh   dksJ t | d  t |d fddtD } fdd|D }dd |D S )Nr7      c                   s   g | ]}| d   qS r   r4   )r:   r   )r   r4   r5   r<   t  rH   z=make_waveform.<locals>.get_color_gradient.<locals>.<listcomp>c                   s    g | ]}d |   |  qS r   r4   )r:   Zmix)c1_rgbc2_rgbr4   r5   r<   u  s     c                 S  s$   g | ]}d d dd |D  qS )#r   c                 s  s$    | ]}t t|d  dV  qdS )r@  02xN)r%   round)r:   valr4   r4   r5   	<genexpr>w  s   " zGmake_waveform.<locals>.get_color_gradient.<locals>.<listcomp>.<genexpr>)r   )r:   itemr4   r4   r5   r<   v  s    )nparrayre   )c1c2r   Zmix_pctsZ
rgb_colors)r?  )rA  rB  r   r5   get_color_gradientp  s   z)make_waveform.<locals>.get_color_gradientr   )   r7      )ZfigsizeZdpiZframeon)leftbottomrighttopoff)r   g      ?r:  )rQ  widthcoloralphaz.pngZbbox_inchesZtightNTtransparentnoneZ	facecolor)i  i     ZRGBAz#FFFFFFc                   sN   t  D ] \}}tjdd}|| | d  ||  |  qd S )Ng?g333333?r:  )rf   rI  randomuniformZ
set_heightZset_y)r   rr   bZrand_height)barcollectionrT   r4   r5   _animate  s
   zmake_waveform.<locals>._animater   d   )repeatZblitframesintervalZpillowZpng)writerZfpscodecsavefig_kwargsz.mp4z-loop1z-iz-filter_complexz[0:v]scale=w=trunc(iw/2)*2:h=trunc(ih/2)*2[bg];[1:v]format=rgba,colorchannelmixer=aa=1.0[ov];[bg][ov]overlay=(main_w-overlay_w*0.9)/2:main_h-overlay_h*0.9/2[output]z-tz-mapz[output]z2:az-c:vZlibx264z-c:aZaacz	-shortestz-yzJ[0:v][1:a]concat=n=1:v=1:a=1[v];[v]scale=1000:400,format=yuv420p[v_scaled]z
[v_scaled]z1:az-vfzcolor=c=#FFFFFF77:s=r   z[bar];[0][bar]overlay=-w+(w/z)*t:H-h:shortest=1)2rY   r\   r   Zaudio_from_filer   r   Zaudio_to_filer   r`   pathisfilerX   shutilwhichRuntimeErrorrE  r?   shaperI  meanpadZreshapeabsmaxr
   r   pltZclfZfigureZsubplots_adjustZaxisZmarginsbarZarangeZsavefigPILZImagerb   resizerJ  Z	fromarraysizer%   newZpastesaver   ZFuncAnimation
subprocess
check_call)#r2  r+  r,  r-  r.  r/  r0  r1  Z
audio_fileZtmp_wavr8  durationrM  Zbins_to_padrV  ZfigZ	bar_alphaZtmp_imgrf  Zwaveform_imgZwaveform_arrayZbg_imgZwaveform_widthZwaveform_heightZbg_widthZ	bg_heightZcomposite_heightZ	compositeZ	img_widthZ
img_heightr_  rb  ZanimZ
output_mp4Z
ffmpeg_cmdr4   )r^  r?  rT   r5   make_waveformA  sD  




	


,






`
r|  c                   @  s   e Zd ZdZd	ddZdS )
r"  a  
    When a subclass of EventData is added as a type hint to an argument of an event listener method, this object will be passed as that argument.
    It contains information about the event that triggered the listener, such the target object, and other data related to the specific event that are attributes of the subclass.

    Example:
        table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])
        gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])
        textbox = gr.Textbox("Hello World!")

        statement = gr.Textbox()

        def on_select(evt: gr.SelectData):  # SelectData is a subclass of EventData
            return f"You selected {evt.value} at {evt.index} from {evt.target}"

        table.select(on_select, None, statement)
        gallery.select(on_select, None, statement)
        textbox.select(on_select, None, statement)
    Demos: gallery_selections, tictactoe
    r#  Block | Noner$  r   c                 C  s   || _ || _dS )z
        Parameters:
            target: The target object that triggered the event. Can be used to distinguish if multiple components are bound to the same listener.
        N)r#  r$  )rq   r#  r$  r4   r4   r5   rs   B  s   
zEventData.__init__N)r#  r}  r$  r   )r   r   r   r   rs   r4   r4   r4   r5   r"  ,  s    r"  infomessagelevelLiteral['info', 'warning']c                 C  s   ddl m} t|jds!|dkrt|  d S |dkrt|  d S |jjjs6td|	  d|  d d S |jjj
j|jj| |d	 d S )
Nr   )contextblocksr~  warningz"Queueing must be enabled to issue z: 'z'.)r   logr  )rl   r  r   Zthread_datar   rV   rW   r  Zenable_queue
capitalizer
  log_messager   )r  r  r  r4   r4   r5   r  K  s    




r  Warning issued.c                 C     t | dd dS )a/  
    This function allows you to pass custom warning messages to the user. You can do so simply with `gr.Warning('message here')`, and when that line is executed the custom message will appear in a modal on the demo.
    Parameters:
        message: The warning message to be displayed to the user.
    r  r  Nr  r  r4   r4   r5   Warning^  s   r  Info issued.c                 C  r  )zT
    Parameters:
        message: The info message to be displayed to the user.
    r~  r  Nr  r  r4   r4   r5   Infoh  s   r  )NNFr   FNNFTTFF)r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r#   r'   r(   r)   r(   r*   r#   r+   r#   r,   r#   r-   r.   r/   r#   )r   r   r   rZ   r   rZ   )NNN)r    r   r   r  r   r  r  r  )rt   r(  )r2  r3  r+  r\   r,  r(   r-  r4  r.  r5  r/  r%   r0  r4  r1  r#   rt   r\   )r~  )r  r\   r  r  )r  )r  r\   )r  )Cr   
__future__r   r   rc   r   r`   rj  ry  r   r   rV   pathlibr   typingr   r   r   r   r   r	   Zmatplotlib.pyplotZpyplotrr  numpyrI  rt  Z	PIL.ImageZgradio_clientr
   r2   Zgradio_client.documentationr   r   Z
matplotlibr   rl   r   r   r   r   Zgradio.contextr   Zgradio.exceptionsr   Zgradio.flaggingr   Zgradio.blocksr   Zgradio.componentsr   rn   r_   r6   r1   r   r   r   r  r'  r   r)  r|  r"  r  r  r  r4   r4   r4   r5   <module>   s     &  
O$ NS
* k	