
    ;3hV                    "   d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	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mZ erdd
lmZmZ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% 	 	 	 	 d9dZ& e        G d de'             Z( e        G d d             Z) e        G d de)             Z* e        G d de)             Z+ e        G d de)             Z, e        G d de)             Z- e        G d de)             Z. e        G d de)             Z/ e        G d  d!e)             Z0 e        G d" d#e)             Z1 e        G d$ d%e)             Z2ejf                   G d& d'             Z4ereeed(ef   df   eeee   df   eeee   ee   edf   ee5ded)   f   e6ed*   eeee   df   ee6df   e6e7e6e6ee'e5ef   e8e'e5ef      df   ee9df   eed+   df   ee5df   ee7ded,   f   ee5df   e6ge(f   Z: G d- d.e5      Z; e       	 	 	 	 d:dd)d/dd0d)d1d0d0dddd,dd0dd2d3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d;d4       Z< e       	 d<dd0d)d1d,dd0dd2d5		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=d6       Z= G d7 d8      Z>y)>zContains all of the events that can be triggered in a gr.Blocks() app, with the exception
of the on-page-load event, which is defined in gr.Blocks().load().    )annotationsN)CallableSequenceSet)partialwraps)TYPE_CHECKINGAnyLiteralUnioncast)document)Template)FileDataFileDataDict)BlockBlockContext	ComponentTimer)python_type_to_json_schema)get_blocks_context)get_cancelled_fn_indicesget_function_paramsget_return_typesc                p   |sy t               }|t        d      t        |t              s|g}g }g |D ]4  }t	        |dd       }|rj                  |       $|j                  |       6 r ddlm |j                  | fdd d       |r&t        |      }|j                  | d d d ddd|d		       y y )
Nz1Cannot cancel outside of a gradio.Blocks context.associated_timerr   r   c                 j    t              dkD  rD  cg c]  }  d       c} S  d      S c c} w )N   F)active)len)_r   timers_to_cancels    M/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/events.py<lambda>z#set_cancel_events.<locals>.<lambda><   s=    '(1, /??e$?  %( ?s   0F)fninputsoutputsshow_apiT)r&   r'   r(   queue
preprocessr)   cancelsis_cancel_function)
r   AttributeError
isinstancelistgetattrappendgradio.componentsr   set_event_triggerr   )	triggersr,   
root_blockregular_cancelscancelr   fn_indices_to_cancelr   r#   s	          @@r$   set_cancel_eventsr:       s     #%JPQQgt$),.O(* +"6+=tD##$45""6*+ +$$
 $ 	% 
	
 7H$$(# 	% 
	
     c                  ,     e Zd Z	 d	 d fdZd Z xZS )
Dependencyc                    t         |   |       || _        || _        t	        t        d|dd      j                  |      | _        	 t	        t        d|dd      j                  |      | _        y)a  
        The Dependency object is usualy not created directly but is returned when an event listener is set up. It contains the configuration
        data for the event listener, and can be used to set up additional event listeners that depend on the completion of the current event
        listener using .then() and .success().

        Demos: chatbot_consecutive, blocks_chained_events
        thenF)trigger_aftertrigger_only_on_successhas_triggersuccessTN)	super__init__r&   r   r   EventListenerlistenerr?   rC   )selftriggerkey_vals	dep_indexr&   r   	__class__s         r$   rE   zDependency.__init__W   s     	" 0'(-!	
 h
		 '(,!	
 h
	r;   c                &     | j                   |i |S N)r&   )rH   argskwargss      r$   __call__zDependency.__call__~   s    tww'''r;   rN   )r   zTimer | None)__name__
__module____qualname__rE   rQ   __classcell__rL   s   @r$   r=   r=   U   s     RV%BN%N(r;   r=   c                      e Zd ZdZddZy)	EventDataa  
    When gr.EventData or one of its subclasses is added as a type hint to an argument of a prediction function, a gr.EventData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener. The gr.EventData object itself contains a `.target` attribute that refers to the component
    that triggered the event, while subclasses of gr.EventData contains additional attributes that are different for each class.

    Example:
        import gradio as gr
        with gr.Blocks() as demo:
            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(value, evt: gr.EventData):
                return f"The {evt.target} component was selected, and its value was {value}."
            table.select(on_select, table, statement)
            gallery.select(on_select, gallery, statement)
            textbox.select(on_select, textbox, statement)
        demo.launch()
    Demos: gallery_selections, tictactoe
    c                     || _         || _        y)z
        Parameters:
            target: The component object that triggered the event. Can be used to distinguish multiple components bound to the same listener.
        N)target_data)rH   rZ   r[   s      r$   rE   zEventData.__init__   s    
 
r;   N)rZ   Block | Noner[   r
   )rR   rS   rT   __doc__rE    r;   r$   rX   rX      s    *r;   rX   c                  $     e Zd ZdZd fdZ xZS )
SelectDataa&  
    The gr.SelectData class is a subclass of gr.EventData that specifically carries information about the `.select()` event. When gr.SelectData
    is added as a type hint to an argument of an event listener method, a gr.SelectData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.

    Example:
        import gradio as gr
        with gr.Blocks() as demo:
            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):
                return f"You selected {evt.value} at {evt.index} from {evt.target}"
            table.select(on_select, table, statement)
            gallery.select(on_select, gallery, statement)
            textbox.select(on_select, textbox, statement)
        demo.launch()
    Demos: gallery_selections, tictactoe
    c                    t         |   ||       |d   | _        	 |d   | _        	 |j	                  d      | _        	 |j	                  d      | _        	 |j	                  dd      | _        y )Nindexvalue	row_value	col_valueselectedT)rD   rE   rb   rc   getrd   re   rf   rH   rZ   datarL   s      r$   rE   zSelectData.__init__   s{    &w-
	 w-
	 #hh{3	 #hh{3	 #hhz48	r;   rZ   r\   ri   r
   rR   rS   rT   r]   rE   rU   rV   s   @r$   r`   r`      s    * r;   r`   c                  $     e Zd ZdZd fdZ xZS )	KeyUpDataan  
    The gr.KeyUpData class is a subclass of gr.EventData that specifically carries information about the `.key_up()` event. When gr.KeyUpData
    is added as a type hint to an argument of an event listener method, a gr.KeyUpData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.

    Example:
        import gradio as gr
        def test(value, key_up_data: gr.KeyUpData):
            return {
                "component value": value,
                "input value": key_up_data.input_value,
                "key": key_up_data.key
            }
        with gr.Blocks() as demo:
            d = gr.Dropdown(["abc", "def"], allow_custom_value=True)
            t = gr.JSON()
            d.key_up(test, d, t)
        demo.launch()
    Demos: dropdown_key_up
    c                P    t         |   ||       |d   | _        	 |d   | _        y )Nkeyinput_value)rD   rE   ro   rp   rh   s      r$   rE   zKeyUpData.__init__   s6    &U	 !%] 3	r;   rj   rk   rV   s   @r$   rm   rm      s    * r;   rm   c                  $     e Zd ZdZd fdZ xZS )DeletedFileDataa  
    The gr.DeletedFileData class is a subclass of gr.EventData that specifically carries information about the `.delete()` event. When gr.DeletedFileData
    is added as a type hint to an argument of an event listener method, a gr.DeletedFileData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr
        def test(delete_data: gr.DeletedFileData):
            return delete_data.file.path
        with gr.Blocks() as demo:
            files = gr.File(file_count="multiple")
            deleted_file = gr.File()
            files.delete(test, None, deleted_file)
        demo.launch()
    Demos: file_component_events
    c                F    t         |   ||       t        di || _        y Nr^   rD   rE   r   filerh   s      r$   rE   zDeletedFileData.__init__  &    &&..		r;   rZ   r\   ri   r   rk   rV   s   @r$   rr   rr      s      r;   rr   c                  $     e Zd ZdZd fdZ xZS )LikeDataa  
    The gr.LikeData class is a subclass of gr.EventData that specifically carries information about the `.like()` event. When gr.LikeData
    is added as a type hint to an argument of an event listener method, a gr.LikeData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr
        def test(value, like_data: gr.LikeData):
            return {
                "chatbot_value": value,
                "liked_message": like_data.value,
                "liked_index": like_data.index,
                "liked_or_disliked": like_data.liked
            }
        with gr.Blocks() as demo:
            c = gr.Chatbot([("abc", "def")])
            t = gr.JSON()
            c.like(test, c, t)
        demo.launch()
    Demos: chatbot_core_components_simple
    c                    t         |   ||       |d   | _        	 |d   | _        	 |j	                  dd      | _        y )Nrb   rc   likedT)rD   rE   rb   rc   rg   r|   rh   s      r$   rE   zLikeData.__init__'  sM    &,0M
	 w-
	 "&'4!8
	r;   rj   rk   rV   s   @r$   rz   rz     s    * r;   rz   c                  $     e Zd ZdZd fdZ xZS )	RetryDataa}  
    The gr.RetryData class is a subclass of gr.Event data that specifically carries information about the `.retry()` event. When gr.RetryData
    is added as a type hint to an argument of an event listener method, a gr.RetryData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr

        def retry(retry_data: gr.RetryData, history: list[gr.MessageDict]):
            history_up_to_retry = history[:retry_data.index]
            new_response = ""
            for token in api.chat_completion(history):
                new_response += token
                yield history + [new_response]

        with gr.Blocks() as demo:
            chatbot = gr.Chatbot()
            chatbot.retry(retry, chatbot, chatbot)
        demo.launch()
    c                P    t         |   ||       |d   | _        	 |d   | _        y Nrb   rc   rD   rE   rb   rc   rh   s      r$   rE   zRetryData.__init__M  4    &,0M
	 w-
	r;   rj   rk   rV   s   @r$   r~   r~   7  s    (	 	r;   r~   c                  $     e Zd ZdZd fdZ xZS )UndoDataa  
    The gr.UndoData class is a subclass of gr.Event data that specifically carries information about the `.undo()` event. When gr.UndoData
    is added as a type hint to an argument of an event listener method, a gr.UndoData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr

        def undo(retry_data: gr.UndoData, history: list[gr.MessageDict]):
            history_up_to_retry = history[:retry_data.index]
            return history_up_to_retry

        with gr.Blocks() as demo:
            chatbot = gr.Chatbot()
            chatbot.undo(undo, chatbot, chatbot)
        demo.launch()
    c                P    t         |   ||       |d   | _        	 |d   | _        y r   r   rh   s      r$   rE   zUndoData.__init__l  r   r;   rj   rk   rV   s   @r$   r   r   Y  s    "	 	r;   r   c                  $     e Zd ZdZd fdZ xZS )EditDataa#  
    The gr.EditData class is a subclass of gr.Event data that specifically carries information about the `.edit()` event. When gr.EditData
    is added as a type hint to an argument of an event listener method, a gr.EditData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr

        def edit(edit_data: gr.EditData, history: list[gr.MessageDict]):
            history_up_to_edit = history[:edit_data.index]
            history_up_to_edit[-1] = edit_data.value
            return history_up_to_edit

        with gr.Blocks() as demo:
            chatbot = gr.Chatbot()
            chatbot.undo(edit, chatbot, chatbot)
        demo.launch()
    c                f    t         |   ||       |d   | _        	 |d   | _        	 |d   | _        y )Nrb   previous_valuerc   )rD   rE   rb   r   rc   rh   s      r$   rE   zEditData.__init__  sI    &,0M
	 $((8#9	 w-
	r;   rj   rk   rV   s   @r$   r   r   x  s    $ r;   r   c                  $     e Zd ZdZd fdZ xZS )DownloadDataa  
    The gr.DownloadData class is a subclass of gr.EventData that specifically carries information about the `.download()` event. When gr.DownloadData
    is added as a type hint to an argument of an event listener method, a gr.DownloadData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr
        def on_download(download_data: gr.DownloadData):
            return f"Downloaded file: {download_data.file.path}"
        with gr.Blocks() as demo:
            files = gr.File()
            textbox = gr.Textbox()
            files.download(on_download, None, textbox)
        demo.launch()
    c                F    t         |   ||       t        di || _        y rt   ru   rh   s      r$   rE   zDownloadData.__init__  rw   r;   rx   rk   rV   s   @r$   r   r          r;   r   c                  $     e Zd ZdZd fdZ xZS )CopyDataa  
    The gr.CopyData class is a subclass of gr.EventData that specifically carries information about the `.copy()` event. When gr.CopyData
    is added as a type hint to an argument of an event listener method, a gr.CopyData object will automatically be passed as the value of that argument.
    The attributes of this object contains information about the event that triggered the listener.
    Example:
        import gradio as gr
        def on_copy(copy_data: gr.CopyData):
            return f"Copied text: {copy_data.value}"
        with gr.Blocks() as demo:
            textbox = gr.Textbox("Hello World!")
            copied = gr.Textbox()
            textbox.copy(on_copy, None, copied)
        demo.launch()
    c                :    t         |   ||       |d   | _        y )Nrc   )rD   rE   rc   rh   s      r$   rE   zCopyData.__init__  s"    &w-
	r;   rj   rk   rV   s   @r$   r   r     r   r;   r   c                  "    e Zd ZU ded<   ded<   y)EventListenerMethodr\   blockstr
event_nameN)rR   rS   rT   __annotations__r^   r;   r$   r   r     s    Or;   r   .F)fullminimalhidden)oncemultiplealways_lastdefaultc            	           e Zd Z fdZdd dddddddf		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Zdd
Zd Ze	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z xZ	S )rF   c                $    t         |   | |      S rN   )rD   __new__)clsr   _args_kwargsrL   s       r$   r   zEventListener.__new__  s    wsJ//r;   Tc                     i S rN   r^   r^   r;   r$   r%   zEventListener.<lambda>  s    R r;   r   NF ssec           
        t         |           || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
xs g | _        | j                  ||||||| j                  | j                        | _        |r@| j                  j                  r)|| j                  j                  z   | j                  _        y y y rN   )rD   rE   rB   config_datar   show_progressr@   rA   callbackdoc
connectionevent_specific_args_setuprG   r]   )rH   r   rB   r   r   r   r@   rA   r   r   r   rL   s              r$   rE   zEventListener.__init__  s     	&&$**'>$ $#6#<" #$$OO	
 4==(($'$--*?*?$?DMM! )3r;   c                    | j                   j                  rAt        | j                   j                        j                  |      }|| j                   _        y y )N)	component)rG   r]   r   render)rH   r   r   s      r$   set_doczEventListener.set_doc  sB    ==  4==0018898MC$'DMM! !r;   c                    t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  
      S rN   )rF   r   rB   r   r   r   r@   rA   r   r   r   )rH   s    r$   copyzEventListener.copy  sa    OOMM((HHOO$$
 	
r;   c                ^   
 dd d d d|d dddddd d d dd dd ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d 
fd
 
_         
_        
_        
_        r(D cg c]  }|j	                  dd	      d
k7  r|d    c}nd }	|	
_        
S c c}w )N	decoratorFT   r         ?c           !     ~   	
 |dk(  r%	 $
fd}t        di d|      S ddlm} t         |      rd j                  v r j                          t        t              rrdndt               }|t        d	 d
      t        !r nd      }|j                  |g|	
"#||| r( D cg c]  }|j                  dd      dk7  r|d    c}nd      \  }}t        |g       r         t         |j                         ||      S c c}w )a  
            Parameters:
                fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
                inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
                outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
                api_name: defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event.
                scroll_to_output: If True, will scroll to output component on completion
                show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
                show_progress_on: Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components.
                queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
                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. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
                max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
                preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
                postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
                cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
                trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
                js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
                concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
                concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
                show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
            r   c                      di dd d	dddddd	d
dddddd
ddd t                fd       }|S )Nr   r&   r'   r(   api_namescroll_to_outputr   show_progress_onr*   batchmax_batch_sizer+   postprocessr,   trigger_modejsconcurrency_limitconcurrency_idr)   c                      | i |S rN   r^   rO   rP   funcs     r$   innerzKEventListener._setup.<locals>.event_trigger.<locals>.wrapper.<locals>.inner  s    #T4V44r;   r^   )r   )r   r   r   r   r   r,   r   r   event_triggerr'   r   r   r(   r   r+   r*   r   r)   r   r   r   s   ` r$   wrapperz<EventListener._setup.<locals>.event_trigger.<locals>.wrappern  s    ! #  & !(	
 "* *: '4 *: $ $ (6 $. %0 !( &2  !" +<#$ (6%& "*', 4[5 !5 !Lr;   Nr   )StreamingInputstreamr   r   zCannot call z$ outside of a gradio.Blocks context.component_proptruefalsename)r+   r   r   r   r   r   r   r   r   r*   r   r   r@   rA   r   r)   r   
time_limitstream_everylike_user_messager   )r=   gradio.components.baser   r/   eventscheck_streamableboolr   r.   r   r4   rg   r:   
get_config)%r   r&   r'   r(   r   r   r   r   r*   r   r   r+   r   r,   r   r   r   r   r)   r   r   r   r   r   r6   event_targetddeprK   	_callback_connection_event_name_event_specific_args_has_trigger_trigger_after_trigger_only_on_successr   s%   ` `````````````````          r$   r   z+EventListener._setup.<locals>.event_trigger6  s   l [ ! ! !: "$D'::=%0X5M&&(-.*7X+-J!$";-/ST  /%4L (99%'!1+!1!"3--,(@)!&%)"3 ( 2%uu-v6'A fI% ? :  NCB  % eS^^%5y"EE%s   !D:8r   r   r   r   ).r   r\   r&   z&Callable | None | Literal['decorator']r'   dComponent | BlockContext | Sequence[Component | BlockContext] | Set[Component | BlockContext] | Noner(   r   r   str | None | Literal[False]r   r   r   $Literal['full', 'minimal', 'hidden']r   &Component | Sequence[Component] | Noner*   r   r   r   r   intr+   r   r   r   r,   ,dict[str, Any] | list[dict[str, Any]] | Noner   1Literal['once', 'multiple', 'always_last'] | Noner   str | Literal[True] | Noner   int | None | Literal['default']r   
str | Noner)   r   r   
int | Noner   floatr   r   returnr=   )r   rB   r   r   rg   r   )r   r   _show_progressr   r   r   r   r   r   r   r   s   `` `````  @r$   r   zEventListener._setup+  s    :E
 
 48%*BPGK"## $DHNR-1AJ)-!%)"%&+=O	FO	F6O	FO	FO	F 2O	F #O	F @O	F  E!O	F" #O	F$ %O	F&  'O	F( )O	F* +O	F, B-O	F. L/O	F0 +1O	F2  ?3O	F4 '5O	F6 7O	F8 #9O	F:  ;O	F<  $=O	F> ?O	F O	Fb $/ $0!!*#.  $ .55)62g= &	  	 -@)s   ;!B*)r   r   rB   r   r   zCallable[..., dict[str, Any]]r   r   r   Callable | Noner@   r   rA   r   r   r   r   Literal['sse', 'stream']r   zlist[dict[str, str]] | None)r   r   )r   )r   r   r   r   r   r   r   r   r   r   r   r   r   zlist[dict[str, str]]r   r   )
rR   rS   rT   r   rE   r   r   staticmethodr   rU   rV   s   @r$   rF   rF     s   0 !5?>D$($((-/4;?#@#@ #@ 3	#@
 <#@ "#@ "#@ "&#@ #@ -#@ 9#@J(

  16iii =i #	i
 #i #'i 3i .i ir;   rF   r   Tr   r   )r   r   r   r   r*   r   r   r+   r   r,   r   r   r   r   r)   r   r   c                  	
 ddl m} t         t              s  g t	        t        t
                  }t        |      rg|dk(  r&	
 fd}t        di d|      S t               }|t        d       -D cg c]  }t        |d       c}ng t        |d      gz   }n;|D cg c]0  }t        |j                  r|j                  nd|j                        2 }} r/ D ]*  }|j                  s|j                  |j                         , |j                  ||	
t        d	 |xs g D              rd
nd|xs g D cg c].  }t	        t         t"           |j$                  xs g       D ]  }| 0 c}}      \  }}t'        |       t        d|j)                         ||      S c c}w c c}w c c}}w )a  
    Sets up an event listener that triggers a function when the specified event(s) occur. This is especially
    useful when the same function should be triggered by multiple events. Only a single API endpoint is generated
    for all events in the triggers list.

    Parameters:
        triggers: List of triggers to listen to, e.g. [btn.click, number.change]. If None, will run on app load and changes to any inputs.
        fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
        inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
        outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
        api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
        scroll_to_output: If True, will scroll to output component on completion
        show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all,
        show_progress_on: Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components.
        queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
        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. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
        max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
        preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
        postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
        cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
        trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
        js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs', return should be a list of values for output components.
        concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
        concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
        show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
        time_limit: The time limit for the function to run. Parameter only used for the `.stream()` event.
        stream_every: The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.
    Example:
        import gradio as gr
        with gr.Blocks() as demo:
            with gr.Row():
                input = gr.Textbox()
                button = gr.Button("Submit")
            output = gr.Textbox()
            gr.on(
                triggers=[button.click, input.submit],
                fn=lambda x: x,
                inputs=[input],
                outputs=[output]
            )
        demo.launch()
    r   )r   Nr   c                     t        fi d dd
dddddd	d
	dddddddddd t                fd       }|S )Nr&   r'   r(   r   r   r   r   r*   r   r   r+   r   r,   r   r   r   r)   r   r   r   c                      | i |S rN   r^   r   s     r$   r   z"on.<locals>.wrapper.<locals>.innerG      T,V,,r;   )onr   )r   r   r   r   r,   r   r   r'   r   r   r(   r   r+   r*   r   r)   r   r   r   r   r   r5   s   ` r$   r   zon.<locals>.wrapper.  s       	
 " "2 , "2    . & (     #4!"  .#$ "%& *'( &)* *+0 4[- - Lr;   z4Cannot call on() outside of a gradio.Blocks context.changeloadc              3  :   K   | ]  }|j                   d k(    yw)r   N)r   ).0ts     r$   	<genexpr>zon.<locals>.<genexpr>v  s     HAq||x'Hs   r   r   )r+   r   r   r   r   r   r   r   r   r*   r   r   r)   r   r   r   r   r   )gradio.blocksr   r/   r   r   rF   r=   r   	Exceptionr   rB   __self__r   r   r4   anyr0   r   r   r:   r   ) r5   r&   r'   r(   r   r   r   r   r*   r   r   r+   r   r,   r   r   r   r   r)   r   r   r   triggers_typedr   r6   inputmethodsr   rI   ar   rK   s    ` ```````````````````           r$   r   r     s   V $h)h.B:(=18<N&% 	[	 	 	> $D'22#%JNOO ! @FFe 1F V45	6 $
  amm

q||T
 
  	3G  !1!12	3  11
)#)+%%!H.2FBHH  %*
$s)Q%:%:%@bA
  


 !9 2 NC< gw'dCNN,i<<[ G

>
s    G5G 23G%0)	r   r*   r   r   r   r   r)   r   r   c       	          	 | dk(  r	f	d}
t        di d|
      S t               }|t        d      ddlm} t        |       }t        |       }d }t        d |D              rt        d	      t        |      D cg c]*  \  }\  }}}} ||r|ndt        |       ||d
z               , }}}}}}t        |      D cg c]!  \  }} |dt        |       ||d
z               # }}}|j                  g | ||dddddd	      \  }}t        d|j                         ||       S c c}}}}}w c c}}w )aC  
    Sets up an API endpoint for a generic function that can be called via the gradio client. Derives its type from type-hints in the function signature.

    Parameters:
        fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
        api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
        queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
        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. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
        max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
        concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
        concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
        show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
        time_limit: The time limit for the function to run. Parameter only used for the `.stream()` event.
        stream_every: The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.
    Example:
        import gradio as gr
        with gr.Blocks() as demo:
            with gr.Row():
                input = gr.Textbox()
                button = gr.Button("Submit")
            output = gr.Textbox()
            def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:
                return a + b, c[a:b]
            gr.api(fn, api_name="add_and_slice")
        _, url, _ = demo.launch()

        from gradio_client import Client
        client = Client(url)
        result = client.predict(
                a=3,
                b=5,
                c=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                api_name="/add_and_slice"
        )
        print(result)
    r   c                Z   	  t         
	
       t                fd       }|S )N)
r&   r   r*   r   r   r   r   r)   r   r   c                      | i |S rN   r^   r   s     r$   r   z#api.<locals>.wrapper.<locals>.inner  r   r;   )apir   )r   r   r   r   r   r   r   r*   r)   r   r   s   ` r$   r   zapi.<locals>.wrapper  sH    !-"3-!%) 4[- - Lr;   Nz5Cannot call api() outside of a gradio.Blocks context.r   )Apic                b    |  d| dz  cxk  rdk  rd S  ddddj                  | dz  d       S )	N
   d      thstndrd)r         )rg   )ns    r$   ordinalzapi.<locals>.ordinal  sL    R1s70b0Tdee0$4D6Q6U6UVWZ\V\^b6cdeer;   c              3  *   K   | ]  }|d    du   yw)r  Nr^   )r   params     r$   r   zapi.<locals>.<genexpr>  s     
358t
3s   zRAPI endpoints must have type hints. Please specify a type hint for all parameters.r   Fr   )r+   r   r   r   r   r   r   r   r*   r   r   r)   r   r   r   )r=   r   r   gradio.components.api_componentr  r   r   r  
ValueError	enumerater   r4   r   )r&   r   r*   r   r   r   r   r)   r   r   r   r6   r  	fn_paramsreturn_typesr  ir"   has_defaultdefault_value_typer'   typer(   r   rK   s    `````````                r$   r
  r
    s   d 
[	 	( $D'22#%JOPP3#B'I#B'Lf 
3
33`
 	
 :C99M  6A5;u 	(Md&u-AEN	
F  !.At 	D,T2GAENCG 
  11

+%%!' 2 NC* dCNN,i<<Es   /D=&Ec                     e Zd Z edd      Z edd      Z edd      Z edd	      Z ed
d      Z edd      Z	 eddd       Z
 edd      Z edd      Z edd      Z edd      Z	 edd      Z edd      Z edd      Z edd      Z ed d!      Z ed"d#      Z ed$d%      Z ed&d'      Z ed(d) d*+      Z ed,d- d. d/d,d0d1d2d3d4d5d6d7d8d9g:      Z ed;d< d= d>d?d@d4gdAB      Z edCdD      Z edEdF      Z edGdH      Z edIdJ      Z edKdL      Z edMdN      Z edOdPdQR      Z edSdTdU dV W      Z  edXdYdZ d[ W      Z! ed\d]      Z" ed^d_      Z# ed`da      Z$ edbdc      Z%yd)eEventsr   a  Triggered when the value of the {{ component }} changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.)r   r  zRThis listener is triggered when the user changes the value of the {{ component }}.clickz.Triggered when the {{ component }} is clicked.double_clickz5Triggered when the {{ component }} is double clicked.submitzdThis listener is triggered when the user presses the Enter key while the {{ component }} is focused.stopzKThis listener is triggered when the user clicks on the stop button or icon.editzjThis listener is triggered when the user edits the {{ component }} (e.g. image) using the built-in editor.c                :    t        | dd       t        | dd      S d S )Neditableuser)r1   setattrr   s    r$   r%   zEvents.<lambda>  s)    5*d+3  'uj&A  r;   )r   r   clearzmThis listener is triggered when the user clears the {{ component }} using the clear button for the component.playzPThis listener is triggered when the user plays the media in the {{ component }}.pausezVThis listener is triggered when the media in the {{ component }} stops for any reason.zeThis listener is triggered when the user reaches the end of the media playing in the {{ component }}.endstart_recordingzSThis listener is triggered when the user starts recording with the {{ component }}.pause_recordingzSThis listener is triggered when the user pauses recording with the {{ component }}.stop_recordingzRThis listener is triggered when the user stops recording with the {{ component }}.focusz?This listener is triggered when the {{ component }} is focused.blurzIThis listener is triggered when the {{ component }} is unfocused/blurred.uploadzQThis listener is triggered when the user uploads a file into the {{ component }}.releasezTThis listener is triggered when the user releases the mouse on this {{ component }}.selectc                    t        | dd      S )N_selectableTr.  r/  s    r$   r%   zEvents.<lambda>P  s    wumTB r;   a  Event listener for when the user selects or deselects the {{ component }}. Uses event data gradio.SelectData to carry `value` referring to the label of the {{ component }}, and `selected` to refer to state of the {{ component }}. See EventData documentation on how to use this event data)r   r   r   c                 
    ddiS )N
streamableFr^   r^   r;   r$   r%   zEvents.<lambda>U      \51 r;   c                    t        | dd      S )N	streamingTr>  r/  s    r$   r%   zEvents.<lambda>V      wuk4@ r;   zEThis listener is triggered when the user streams the {{ component }}.r   r   zfloat = 0.5zThe latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.)r   r#  r   r   zfloat | None = NonezVThe time limit for the function to run. Parameter only used for the `.stream()` event.r   )r   r#  r   r   )r   r   r   r   r   r   likec                 
    ddiS )NlikeableFr^   r^   r;   r$   r%   zEvents.<lambda>j  s    Z/ r;   c                    t        | dd      S )NrG  Tr>  r/  s    r$   r%   zEvents.<lambda>k  s    wuj$? r;   r   zbool = FalsezEWhether to display the like buttons for user messages in the chatbot.a  This listener is triggered when the user likes/dislikes from within the {{ component }}. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.)r   r   r   r   example_selecta"  This listener is triggered when the user clicks on an example from within the {{ component }}. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.option_selecta!  This listener is triggered when the user clicks on an option from within the {{ component }}. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.r   zSThis listener is triggered when the {{ component }} initially loads in the browser.key_upz\This listener is triggered when the user presses a key while the {{ component }} is focused.applyzpThis listener is triggered when the user applies changes to the {{ component }} through an integrated UI action.deletea  This listener is triggered when the user deletes and item from the {{ component }}. Uses event data gradio.DeletedFileData to carry `value` referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event datatickzOThis listener is triggered at regular intervals defined by the {{ component }}.r   )r   r   undozWThis listener is triggered when the user clicks the undo button in the chatbot message.c                    t        | dd      S )N	_undoableTr>  r/  s    r$   r%   zEvents.<lambda>  rD  r;   c                 
    ddiS )NrQ  Fr^   r^   r;   r$   r%   zEvents.<lambda>  s    [%0 r;   )r   r   r   retryzXThis listener is triggered when the user clicks the retry button in the chatbot message.c                    t        | dd      S )N
_retryableTr>  r/  s    r$   r%   zEvents.<lambda>  s    wulDA r;   c                 
    ddiS )NrU  Fr^   r^   r;   r$   r%   zEvents.<lambda>  rA  r;   expandz@This listener is triggered when the {{ component }} is expanded.collapsezAThis listener is triggered when the {{ component }} is collapsed.downloadzThis listener is triggered when the user downloads a file from the {{ component }}. Uses event data gradio.DownloadData to carry information about the downloaded file as a FileData object. See EventData documentation on how to use this event datar   zThis listener is triggered when the user copies content from the {{ component }}. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event dataN)&rR   rS   rT   rF   r   r  r&  r'  r(  r)  r*  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r:  r;  r   rE  rI  rJ  r   rK  rL  rM  rN  rO  rS  rW  rX  rY  r   r^   r;   r$   r%  r%    s    nF `E ''WXE SL rF YD xD {E ^D dE sD sC $aO $aO #`N VE WD _F bG B nF
 1@S '% j %-o")	
F* /? ,&^
 cD # qN " pM aD jF ~E  WF ]D
 e@0	D fA1	E NF OH  EH  iDr;   r%  )r5   zSequence[EventListenerMethod]r,   z,None | dict[str, Any] | list[dict[str, Any]])Nr   NN),r5   z>Sequence[EventListenerCallable] | EventListenerCallable | Noner&   z0Callable[..., Any] | None | Literal['decorator']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   r   r)   r   r   r   r   r   r   r=   )r   )r&   zCallable | Literal['decorator']r   r   r*   r   r   r   r   r   r   r   r   r   r)   r   r   r   r   r   r   r=   )?r]   
__future__r   dataclassescollections.abcr   r   r   	functoolsr   r   typingr	   r
   r   r   r   gradio_client.documentationr   jinja2r   gradio.data_classesr   r   r   r   r   r   r3   r   gradio_client.utilsr   gradio.contextr   gradio.utilsr   r   r   r:   dictr=   rX   r`   rm   rr   rz   r~   r   r   r   r   	dataclassr   r   r   r   r0   r   EventListenerCallablerF   r   r
  r%  r^   r;   r$   <module>rh     s  F #  3 3 $  1  6<<' : - X X2
+2
92
j 
)( )( )(X 
  > 
+ + +\ 
!	 ! !H 
i  2 
#y # #L 
	  B 
y  < 
 y    F 
9  0 
y  0   
 $(38$d*+)Xi0$67%%(9*=y$NO#tWU^+,/0)Xi0$67$*$sCx.$tCH~"6<=%+';<dBC#t)#tWY//0#t)'	
* 	+	4fC fR 
OS;F
 
 h= -1":@?C<@FJ%)9B!%!=h=Lh=8h=h=h= *h= h=  8!h=" =#h=$ %h=& 'h=( )h=* +h=, -h=. :/h=0 D1h=2 	#3h=4 75h=6 7h=8 9h=: ;h=< =h=> ?h= h=V 
*5{= -19B!%!{='{= *{= 	{=
 {= {= 7{= {= {= {= {= {= {=|j jr;   