o
    e                    @  s  U 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Zd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZm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$m%Z% d dl&m'Z' d dl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m!Z!m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8m9Z9m:Z: d dl;m<Z<m=Z=m>Z>m?Z? d dl@mAZB d dl@mCZD d dlEmFZFmGZGmHZHmIZImJZJ d dlKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZS zd dlTZTW n eUy   dZTY nw e%d erd dlVmWZW d dlXmYZY dd e0Z e0A e0[ e0\ e0] fD Z^de_d< G dd dZ`G dd  d e`ZaG d!d" d"Zbd<d=d)d*Zcd>d0d1Zdd<d?d4d5Zee$d6d7d8d9G d:d; d;eaZfdS )@    )annotationsN)abstractmethod)defaultdict)Path)
ModuleType)TYPE_CHECKINGAnyAsyncIteratorCallableLiteralcast)CapacityLimiter)serializing)utils)documentset_documentation_group)version)
	analytics
componentsexternal
networkingqueueingroutesstringsthemesr   
wasm_utils)Context)check_deprecated_parameterswarn_deprecation)DuplicateBlockErrorInvalidApiNameErrorInvalidBlockError)	EventDatacreate_trackerskipspecial_args)Default)
ThemeClass)BINARY_FILENAMEBINARY_FOLDERBINARY_PATH
BINARY_URLCURRENT_TUNNELS)GRADIO_VERSIONTupleNoPrintcheck_function_inputs_matchcomponent_or_layout_classconcurrency_count_warningdelete_noneget_cancel_functionget_continuous_fnblocks)FastAPI)	Componentc                 C  s   i | ]}|j |qS  )name).0tr8   r8   =D:\Projects\ConvertPro\env\Lib\site-packages\gradio/blocks.py
<dictcomp>P   s    r=   zdict[str, Theme]BUILT_IN_THEMESc                   @  s   e Zd ZddddddddEddZdd Zdd ZdFddZdGddZ															dHdId:d;Zd<d= Z	e
edJd?d@ZedKdCdDZdS )LBlockTNF)renderelem_idelem_classesvisibleroot_url_skip_init_processingr@   boolrA   
str | NonerB   list[str] | str | NonerC   rD   rE   c                K  s|   t j| _t  jd7  _|| _|| _t|tr|gn|| _|| _t	
d| _|| _d | _d| _|r4|   t| jj|d d S )N       Fkwargs)r   id_idrC   rA   
isinstancestrrB   rD   secretsZtoken_urlsafeshare_tokenrE   parentis_renderedr@   r   	__class____name__)selfr@   rA   rB   rC   rD   rE   rL   r8   r8   r<   __init__]   s   zBlock.__init__c                 C  s~   t jdur| jt jjv rtd| j dt jdur t j|  t jdur=| t jj| j< d| _t| t	j
r=t jj| j | S )z9
        Adds self into appropriate BlockContext
        NA block with id: 1 has already been rendered in the current Blocks.T)r   
root_blockrN   r5   r   blockaddrT   rO   r   IOComponenttemp_file_setsappendZ
temp_filesrW   r8   r8   r<   r@   y   s   

zBlock.renderc                 C  sl   t jdurz	t jj|  W n	 ty   Y nw t jdur4zt jj| j= d| _W | S  t	y3   Y | S w | S )z
        Removes self from BlockContext if it has been rendered (otherwise does nothing).
        Removes self from the layout and collection of blocks, but does not delete any event triggers.
        NF)
r   r\   childrenremove
ValueErrorr[   r5   rN   rT   KeyErrorra   r8   r8   r<   unrender   s    

zBlock.unrenderreturnrP   c                 C  s$   t | dr| jjj S | jj S )z
        Gets block's class name.

        If it is template component it gets the parent's class name.

        @return: class name
        Zis_template)hasattrrU   __base__rV   lowerra   r8   r8   r<   get_block_name   s
   

zBlock.get_block_nametype[BlockContext] | Nonec                 C  s   d S Nr8   ra   r8   r8   r<   get_expected_parent   s   zBlock.get_expected_parentfull   
event_namefnCallable | Noneinputs3Component | list[Component] | set[Component] | Noneoutputs"Component | list[Component] | None
preprocesspostprocessscroll_to_outputshow_progressapi_namestr | None | Literal[False]js	no_targetqueuebool | Nonebatchmax_batch_sizeintcancelslist[int] | Noneeveryfloat | Nonecollects_event_datatrigger_after
int | Nonetrigger_only_on_successtuple[dict[str, Any], int]c                 C  s  t |trd}t|dd d}nd}|du rg }nt |ts!|g}t |tr/t|dd d}n|du r6g }nt |ts>|g}|durJ|sJt||| tjdu rVt| d|durb|d	krbtd
|rq|rqtd| d| d|r{|r{t	||}n|rtd|rt
|nd\}}}tjjt|||||||du |	dur|	durt|	dd tjjD }|	|krtd|	 d|  |}	|du r|du}i d|s| jgng d|ddd |D ddd |D d|dud|
d|du rdn|d|	dt rdn|d|d |d!|d"|d#|pg d$t|t|p%t|d%d&|d'|d(|i}tjj| |ttjjd) fS )*aU	  
        Adds an event to the component's dependencies.
        Parameters:
            event_name: event name
            fn: Callable function
            inputs: input list
            outputs: output list
            preprocess: whether to run the preprocess methods of components
            postprocess: whether to run the postprocess methods of components
            scroll_to_output: whether to scroll to output of dependency on trigger
            show_progress: whether to show progress animation while running.
            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, 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.
            js: Experimental parameter (API may change): 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
            no_target: if True, sets "targets" to [], used for Blocks "load" event
            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: whether this function takes in a batch of inputs
            max_batch_size: the maximum batch size to send to the function
            cancels: a list of other events to cancel when this event 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.
            every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
            collects_event_data: whether to collect event data for this event
            trigger_after: if set, this event will be triggered after 'trigger_after' function index
            trigger_only_on_success: if True, this event will only be triggered if the previous event was successful (only applies if `trigger_after` is set)
        Returns: dependency information, dependency index
        Tc                 S     | j S rm   rN   xr8   r8   r<   <lambda>       z)Block.set_event_trigger.<locals>.<lambda>)keyFNc                 S  r   rm   r   r   r8   r8   r<   r      r   z?() and other events can only be called within a Blocks context.r   z(Parameter every must be positive or NonezCannot run z event in a batch and every zA seconds. Either batch is True or every is non-zero but not both.z.Cannot set a value for `every` without a `fn`.NNNc                 S     g | ]}|d  qS r|   r8   r:   depr8   r8   r<   
<listcomp>      z+Block.set_event_trigger.<locals>.<listcomp>	api_name  already exists, using targetstriggerrt   c                 S     g | ]}|j qS r8   r   r:   r\   r8   r8   r<   r         rv   c                 S  r   r8   r   r   r8   r8   r<   r     r   
backend_fnr~   r   r|   rz   r{   r   r   r   r   types)Z
continuous	generatorr   r   r   rI   )rO   setsortedlistr/   r   r[   AttributeErrorrd   r4   r%   fnsr`   BlockFunctionr   append_unique_suffixdependencieswarningswarnrN   	get_spacerF   inspectisgeneratorfunctionlen)rW   rq   rr   rt   rv   rx   ry   rz   r{   r|   r~   r   r   r   r   r   r   r   r   r   inputs_as_dict_progress_indexZevent_data_index	api_name_
dependencyr8   r8   r<   set_event_trigger   s   
/



	

zBlock.set_event_triggerc                 C  s   | j | j| j| jdS )NrC   rA   rB   rD   r   ra   r8   r8   r<   
get_config5  s
   zBlock.get_configdictc                  K  s   i S rm   r8   rK   r8   r8   r<   update=  s   zBlock.updategeneric_updatedict[str, Any]c                 C  s"   |  }|d= | jdi |}|S )N__type__r8   )copyr   )clsr   Zspecific_updater8   r8   r<   get_specific_updateB  s   zBlock.get_specific_update)r@   rF   rA   rG   rB   rH   rC   rF   rD   rG   rE   rF   )rg   rP   )rg   rl   )TTFro   NNFNFrp   NNNNF)(rq   rP   rr   rs   rt   ru   rv   rw   rx   rF   ry   rF   rz   rF   r{   rP   r|   r}   r~   rG   r   rF   r   r   r   rF   r   r   r   r   r   r   r   r   r   r   r   rF   rg   r   )rg   r   )r   r   rg   r   )rV   
__module____qualname__rX   r@   rf   rk   rn   r   r   staticmethodr   r   classmethodr   r8   r8   r8   r<   r?   \   sF    

	 	r?   c                   @  sT   e Zd Z		ddddZdd	d
Zdd ZdddZdd ZddddZdd Z	dS )BlockContextTrC   rF   r@   c                 K  s"   g | _ tj| f||d| dS )z
        Parameters:
            visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
            render: If False, this will not be included in the Blocks config file at all.
        )rC   r@   N)rb   r?   rX   )rW   rC   r@   rL   r8   r8   r<   rX   K  s   zBlockContext.__init__childr?   c                 C  s   | j | d S rm   )rb   r`   rW   r   r8   r8   r<   	add_childY  s   zBlockContext.add_childc                 C  s   t j| _| t _| S rm   )r   r\   rS   ra   r8   r8   r<   	__enter__\  s   zBlockContext.__enter__c                 C  s   | |_ | j| d S rm   )rS   rb   r`   r   r8   r8   r<   r]   a  s   zBlockContext.addc                 C  s   g }d }| j D ]C}| }|rt| |rd }|| q|d ur+t||r+|| n|dd}| |_|| || tjrG|tjj|j	< ||_q|| _ d S )NF)r@   )
rb   rn   rO   r`   r   rS   r   r[   r5   rN   )rW   rb   Zpseudo_parentr   Zexpected_parentr8   r8   r<   fill_expected_parentse  s&   





z"BlockContext.fill_expected_parentsNexc_typetype[BaseException] | Nonec                 G  s0   | j t_|d ur
d S t| ddr|   d S d S )NZallow_expected_parentsT)rS   r   r\   getattrr   rW   r   argsr8   r8   r<   __exit__|  s   zBlockContext.__exit__c                 C  s   |S )zO
        Any postprocessing needed to be performed on a block context.
        r8   )rW   yr8   r8   r<   ry     s   zBlockContext.postprocess)TT)rC   rF   r@   rF   )r   r?   rm   r   r   )
rV   r   r   rX   r   r   r]   r   r   ry   r8   r8   r8   r<   r   J  s    

r   c                   @  s2   e Zd Z	ddddZdd Zdd Zdd ZdS )r   Frr   rs   rt   list[Component]rv   rx   rF   ry   r   tracks_progressc                 C  s\   || _ || _|| _|| _|| _|| _d| _d| _|| _|d ur%t	|ddnd | _
|   d S )Nr   rV   rr   )rr   rt   rv   rx   ry   r   total_runtime
total_runsr   r   r9   spaces_auto_wrap)rW   rr   rt   rv   rx   ry   r   r   r8   r8   r<   rX     s   
zBlockFunction.__init__c                 C  s.   t d u rd S t d u rd S t | j| _d S rm   )spacesr   r   Zgradio_auto_wraprr   ra   r8   r8   r<   r     s
   zBlockFunction.spaces_auto_wrapc                 C  s   t | j| j| jdS )N)rr   rx   ry   )rP   r9   rx   ry   ra   r8   r8   r<   __str__  s   zBlockFunction.__str__c                 C  s   t | S rm   )rP   ra   r8   r8   r<   __repr__     zBlockFunction.__repr__N)F)rr   rs   rt   r   rv   r   rx   rF   ry   rF   r   rF   r   rF   )rV   r   r   rX   r   r   r   r8   r8   r8   r<   r     s    		r   Tr\   update_dictr   ry   rF   c                 C  s   | dddkr| |}| dtjju r|d |dd}|dur-|r)dnd|d	< t|d
d}d|v rQ|rQt| tjsHJ d| j	 d| 
|d |d< |S )a  
    Converts a dictionary of updates into a format that can be sent to the frontend.
    E.g. {"__type__": "generic_update", "value": "2", "interactive": False}
    Into -> {"__type__": "update", "value": 2.0, "mode": "static"}

    Parameters:
        block: The Block that is being updated with this update dictionary.
        update_dict: The original update dictionary
        postprocess: Whether to postprocess the "value" key of the update dictionary.
    r    r   valueinteractiveNZdynamicZstaticmodeT)Z
skip_valuez
Component z does not support value)getr   r   	_KeywordsZNO_VALUEpopr2   rO   r^   rU   ry   )r\   r   ry   r   prediction_valuer8   r8   r<   postprocess_update_dict  s    

r   outputs_ids	list[int]predictionsrg   list | dictc                 C  s   dd |D }t |r9dd | D }| D ]\}}|j| vr'td| d| |j}|||< qt|}|S t|rAtd|S )a}  
    Converts a dictionary of component updates into a list of updates in the order of
    the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
    E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
    Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
    c                 S  s   g | ]}t |tqS r8   )rO   r?   )r:   r   r8   r8   r<   r     s    z2convert_component_dict_to_list.<locals>.<listcomp>c                 S  s   g | ]}t  qS r8   )r$   )r:   r   r8   r8   r<   r     r   zReturned component z% not specified as output of function.zReturned dictionary included some keys as Components. Either all keys must be Components to assign Component values, or return a List of values to assign output values in order.)allitemsrN   rd   indexr   resolve_singletonany)r   r   Zkeys_are_blocksZreordered_predictions	componentr   Zoutput_indexr8   r8   r<   convert_component_dict_to_list  s"   	



r   config	serializec                 C  s  i i d}|  dd}t|  ddtdk}t| d D ]\}}g g d}d	}|d
 }	|	D ]}
| d D ]
}|d |
krA nq7d} n|d }|tjv rPq1| ds^|tjvr^d} n|tjv rdq1|d  dd|
 }tj|  }| dr|r|d }|d d }nt	|tj
sJ | }| d }|d }|r|d r| }t	|tjr|d  dddkr| }t|}tj| j}|d ||d || ddd| ||d q1|d  }|D ]}| d D ]
}|d |kr nqd} n|d }|tjv rq| ds|tjvrd} n|d  dd!| }tj|  }| dr;|r;|d }|d d }nt	|tj
sDJ | }| d }|d }|rt|d rt| }t	|tjrt|d  dddkrt| }t|}tj| j}|d" ||d || ddd| |d# q|d$ sd}|rq|d% dur|d% d	ur||d& d'|d%  < q|d% d	u s|d(ks|d)krq||d* t|< q|S )+a  
    Gets the information needed to generate the API docs from a Blocks config.
    Parameters:
        config: a Blocks config dictionary
        serialize: If True, returns the serialized version of the typed information. If False, returns the raw version.
    )named_endpointsunnamed_endpointsr   Nr   z2.0z3.28.3r   )
parametersreturnsFrt   r   rM   Ttype
serializerpropslabelZ
parameter_api_infoexample_inputsZ
serializedrawinfoserialized_infoZ
file_countsingler   descriptionr   )r   r  )r   r   python_typer   Zexample_inputr   rv   Zvalue_r   )r   r   r  r   r   r   r|   r   /Z	interfaceZtabbed_interfacer   )r   r   parseVersion	enumerateclient_utilsZSKIP_COMPONENTSr   ZCOMPONENT_MAPPINGrO   Serializabler   r   r  ZFileSerializableZ_multiple_file_serialized_infoZjson_schema_to_python_typerV   r`   
capitalizerP   )r   r   r   r   Zafter_new_formatdr   Zdependency_infoZskip_endpointrt   ir   r   r   r   r  ZexampleZpython_infor  Zserializer_namerv   or8   r8   r<   get_api_info  s   













r  launchr   	integrateloadc                      s  e Zd ZdZ					ddƇ fddZedd ZedddZdd Z	dd Z
edd Zd d! Zddd&d'Zd"dd(dd*d+Z				ddd5d6Zdd8d9Zdd;d<Zdd=d>ZddAdBZddEdFZddHdIZddOdPZ					dddUdVZdWdX ZdYdZ Zd[d\ Zd]d^ Zddׇ fdadbZ						c	d		c	e	f	f		ddddddgdd|d}Zd~d Zee  					f	ddddZ!dd Z"		c		c					c	c			c								f	c	f					f	ddddZ#			ddddZ$ddddZ%dddZ&dd Z'dd Z(dddĄZ)  Z*S )Blocksa  
    Blocks is Gradio's low-level API that allows you to create more custom web
    applications and demos than Interfaces (yet still entirely in Python).


    Compared to the Interface class, Blocks offers more flexibility and control over:
    (1) the layout of components (2) the events that
    trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
    which can trigger the next level of outputs). Blocks also offers ways to group
    together related demos such as with tabs.


    The basic usage of Blocks is as follows: create a Blocks object, then use it as a
    context (with the "with" statement), and then define layouts, components, or events
    within the Blocks context. Finally, call the launch() method to launch the demo.

    Example:
        import gradio as gr
        def update(name):
            return f"Welcome to Gradio, {name}!"

        with gr.Blocks() as demo:
            gr.Markdown("Start typing below and then click **Run** to see the output.")
            with gr.Row():
                inp = gr.Textbox(placeholder="What is your name?")
                out = gr.Textbox()
            btn = gr.Button("Run")
            btn.click(fn=update, inputs=inp, outputs=out)

        demo.launch()
    Demos: blocks_hello, blocks_flipper, blocks_speech_text_sentiment, generate_english_german, sound_alert
    Guides: blocks-and-event-listeners, controlling-layout, state-in-blocks, custom-CSS-and-JS, custom-interpretations-with-blocks, using-blocks-like-functions
    Nr5   GradiothemeTheme | str | Noneanalytics_enabledr   r   rP   titlecssrG   c              
     s  d _ |du rt }n<t|trG| tv rt|  }n*zt|}W n" tyF } zt	
d| dt|  t }W Y d}~nd}~ww t|tsTt	
d t }| _|  _|j _d _d _d _d _tt _d _|durtj|rt|}|  _W d   n1 sw   Y  n| _|dur|nt  _ jrt j!st"j#tj$d}	|	%  nd	tj&d
< t' j(dddi| i  _)g  _*g  _+| _,d _-d _.d _/d _0d _1d _2t34  _5d _6d _7t8t9dd _:t;<d _=g  _>| _?d _@d _Ad _Bd _Cd _Dd _Ed _Fd _Gg  _Hg  _Itj&Jdd _KtL  _M jrWtN fddtO D  }
 j, jdu jjP|
tQd}tR| dS dS )a  
        Parameters:
            theme: a Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the HF Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
            analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
            mode: a human-friendly name for the kind of Blocks or Interface being created.
            title: The tab title to display when this is opened in a browser window.
            css: custom css or path to custom css file to apply to entire Blocks
        NzCannot load z. Caught Exception: z1Theme should be a class loaded from gradio.themesF(   T)targetTrueZHF_HUB_DISABLE_TELEMETRYr@   ZGRADIO_WATCH_DIRS@   GRADIO_ROOT_PATHr   c                 3  s"    | ]} j  | kV  qd S rm   )r  to_dict)r:   Zbuilt_in_themera   r8   r<   	<genexpr>  
    
z"Blocks.__init__.<locals>.<genexpr>)r   Z
custom_cssr  is_custom_themer   r8   )SlimiterDefaultThemerO   rP   rj   r>   ThemeZfrom_hub	Exceptionr   r   r  Z_get_theme_cssZ	theme_cssZ_stylesheetsstylesheetsencryptshareenable_queuemax_threadsr   r   pending_streams
show_errorospathexistsopenreadr  r   r  r   IS_WASM	threadingThreadZversion_checkstartenvironsuperrX   r5   r   r   r   
is_running	local_url	share_urlwidthheightapi_openr   r   space_idfavicon_pathauthrF   getenvdev_moderandomgetrandbitsapp_idr_   r  show_apipredictinput_componentsoutput_componentsrV   api_modeprogress_tracking
ssl_verifyallowed_pathsblocked_pathsr   	root_pathr   	root_urlsr   valuesr9   r-   Zinitiated_analytics)rW   r  r  r   r  r  rL   eZcss_filer;   r#  datarU   ra   r<   rX     s   








zBlocks.__init__c                 C  s   ddl m} t|ddS )Nr   )reload_threadZrunning_reloadF)Zgradio.reloadrW  r   )rW   rW  r8   r8   r<   _is_running_in_reload_thread
  s   z#Blocks._is_running_in_reload_threadr   r   r   list[Callable]rD   rg   c                   s  t |}|d   D ]}d|d v r#|d |d d  |d d= q|dd}i hd( fd
dfdddg}t|d}tjpM|d< |d d  d}t|d |D ]m\}	}
|	d dkrlqa|D ]}|	|d qn|	d}|	d}|	d |	dd fdd|	d D |	d< fdd|	d D |	d< |	dd d |	d!< d |	d"< |D ]}| j	d)||
d#|	d }	|du r|	}qqa|rtjr|d g|_
d$d |d D |_d%d |d D |_d&|_d'|_W d   n1 sw   Y  |_|S )*a  
        Factory method that creates a Blocks from a config and list of functions. Used
        internally by the gradio.external.load() method.

        Parameters:
        config: a dictionary containing the configuration of the Blocks.
        fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
        root_url: an external url to use as a root URL when serving files for components in the Blocks.
        r   styler   r  defaultrM   r   rg   r?   c                   s    D ]
}|d | kr nqt d|  t|d }|d dd  |d dd  |d dd u r= d|d d< n	|d d  |d
i |d dd	i}|S )NrM   zCannot find block with id r   r   r9   rD   r  rE   Tr8   )rd   r0   r   r   r]   )rM   block_configr   r\   )components_configrD   rR  r8   r<   get_block_instance+  s   z.Blocks.from_config.<locals>.get_block_instancec              	     s~   | D ]:}|d } |}||< | d}|d ur<t|ts&J d| d| | W d    n1 s7w   Y  qd S )NrM   rb   zInvalid config, Block with id z( has children but is not a BlockContext.)r   rO   r   )Zchildren_listZchild_configrM   r\   rb   )r^  iterate_over_childrenoriginal_mappingr8   r<   r_  ?  s    


z1Blocks.from_config.<locals>.iterate_over_childrenr   )r  r   layoutrb   Nr   r   Z
fake_eventr   r   Zdocumentationc                      g | ]} | qS r8   r8   r:   r  r`  r8   r<   r   g      z&Blocks.from_config.<locals>.<listcomp>rt   c                   rb  r8   r8   r:   r  rd  r8   r<   r   j  re  rv   Zstatus_trackerFrx   ry   )rq   rr   c                 S     g | ]}t jj| qS r8   r   r[   r5   rc  r8   r8   r<   r   {      c                 S  rg  r8   rh  rf  r8   r8   r<   r   ~  ri  Z	InterfaceT)rM   r   rg   r?   r8   )r   deepcopyr   r   r  r   r[   zipr   r   rI  rJ  rK  rV   rL  rR  )r   r   r   rD   Zcomponent_configr  Zderived_fieldsr5   Zfirst_dependencyr   rr   fieldr   r   r  r8   )r]  r^  r_  r`  rD   rR  r<   from_config  sz   










4zBlocks.from_configc                 C  s   |   S rm   )r   ra   r8   r8   r<   r     r   zBlocks.__str__c                 C  s   t dd | jD }d| d}|ddt |  7 }t| jD ]=\}}|d r]|d| 7 }|d	7 }|d
 D ]}| j| }|d| 7 }q7|d7 }|d D ]}| j| }|d| 7 }qNq |S )Nc                 S  s   g | ]}|d  r|qS )r   r8   )r:   r  r8   r8   r<   r     s    z#Blocks.__repr__.<locals>.<listcomp>zGradio Blocks instance: z backend functions
-r   z

fn_index=z	
 inputs:rt   z
 |-z

 outputs:rv   )r   r   r	  r5   )rW   Znum_backend_fnsreprr  r   input_idr\   	output_idr8   r8   r<   r     s    

zBlocks.__repr__c                 C  s   t dd | j D S )z>Return whether the app expects user to authenticate via OAuth.c                 s  s"    | ]}t |tjtjfV  qd S rm   )rO   r   ZLoginButtonZLogoutButtonr   r8   r8   r<   r!    r"  z'Blocks.expects_oauth.<locals>.<genexpr>)r   r5   rS  ra   r8   r8   r<   expects_oauth  s   zBlocks.expects_oauthc           	        s  t jd ur| jt jjv rtd| j dtt jj| j}|D ]}t| j| tj	s0tdq!t jj
| j t jj| j tt jj t| jD ]u\}}|d }|d ur||dur|t|dd t jjD }||kr|td| d	|  ||d<  fd
d|d D |d< |dd ur|d   7  < |d rdd |d D }tt|d g g ddd}|t jj | < t jj| qLt jj| j t jj
| j t jd urt jj| j | S )NrY   rZ   z<At least one block in this Blocks has already been rendered.r|   Fc                 S  r   r   r8   r   r8   r8   r<   r     r   z!Blocks.render.<locals>.<listcomp>r   r   c                   s   g | ]}|  qS r8   r8   )r:   cZdependency_offsetr8   r<   r     re  r   r   c                 S  rg  r8   )r   r[   r   rc  r8   r8   r<   r     s    
r   T)r   r[   rN   r5   r   r   intersectionrO   r   Stater   r   extendr   r   r	  r   r   r   r   r   r   r3   r`   r_   rR  r\   rb   )	rW   Zoverlapping_idsrM   r  r   r|   r   Zupdated_cancelsZnew_fnr8   ru  r<   r@     sf   




zBlocks.renderr   fn_indexr   rF   c                 C  s   | j | }| j| }t|jrdS t|jrdS |d D ]}| j| }t|ddr. dS q|d D ]}| j| }t|ddrC dS q3dS )zVChecks if a particular Blocks function is callable (i.e. not stateful or a generator).Frt   statefulrv   T)r   r   r   isasyncgenfunctionrr   r   r5   r   )rW   ry  block_fnr   rq  r\   rr  r8   r8   r<   is_callable  s"   



zBlocks.is_callable)ry  r|   r|   c          	        s    dur t  fddt| jD d}|du rtd  |}| |s)tdt|}| ||}| j| d }|rCdd |D }tj	| j
||di d	}|d
 }|r[dd |D }| ||}t|}|S )a  
        Allows Blocks objects to be called as functions. Supply the parameters to the
        function as positional arguments. To choose which function to call, use the
        fn_index parameter, which must be a keyword argument.

        Parameters:
        *inputs: the parameters to pass to the function
        fn_index: the index of the function to call (defaults to 0, which for Interfaces, is the default prediction function)
        api_name: The api_name of the dependency to call. Will take precedence over fn_index.
        Nc                 3  s&    | ]\}}| d  kr|V  qdS )r|   N)r   )r:   r  r  r   r8   r<   r!    s    z"Blocks.__call__.<locals>.<genexpr>z%Cannot find a function with api_name zThis function is not callable because it is either stateful or is a generator. Please use the .launch() method instead to create an interactive user interface.r   c                 S  s   g | ]}|gqS r8   r8   r:   inpr8   r8   r<   r     r   z#Blocks.__call__.<locals>.<listcomp>)ry  rt   requeststaterU  c                 S  r   r   r8   )r:   outr8   r8   r<   r      r   )nextr	  r   r    r}  rd   r   serialize_datar
  Zsynchronize_asyncprocess_apideserialize_datar   r   )	rW   ry  r|   rt   Zinferred_fn_indexZprocessed_inputsr   rv   Zprocessed_outputsr8   r   r<   __call__  sD   


zBlocks.__call__processed_input	list[Any]iteratorAsyncIterator[Any] | Nonerequests,routes.Request | list[routes.Request] | Noneevent_id
event_dataEventData | Nonec                   s  | j | }|jsJ d| dd}t|tr|d n|}	t }
t|j| |}|du r|jr:tt	|j
|g}t|j||	|\}}}|durM|| nd}|dure|duret| |||j\}}|||< t|rr|| I dH }ntjj|g|R d| jiI dH }nd}t|st|r| jstdz#|du rttt |}t|rt|| j}t|I dH }d}W n$ ty   t| j | !d	}|d
krt"j#j$nt"j#j$f| }d}Y nw t |
 }||||dS )a  
        Calls function with given index and preprocessed input, and measures process time.
        Parameters:
            fn_index: index of function to call
            processed_input: preprocessed input to pass to function
            iterator: iterator to use if function is a generator
            requests: requests to pass to function
            event_id: id of event in queue
            event_data: data associated with event trigger
        zfunction with index z not defined.Fr   Nr$  z'Need to enable queue to use generators.Trv   rI   )
predictiondurationis_generatingr  )%r   rr   rO   r   timer   Zget_function_with_localsr   r   rk  rt   r%   r#   Z
track_tqdmr   iscoroutinefunctionanyio	to_threadZrun_syncr$  r   r{  r+  rd   r   r	   r   isgeneratorZSyncToAsyncIteratorZasync_iterationStopAsyncIterationr   r   r   r   r   FINISHED_ITERATING)rW   ry  r  r  r  r  r  r|  r  r  r7  rr   r   r   Zprogress_trackerr  Z	n_outputsr  r8   r8   r<   call_function'  sl   





	zBlocks.call_functionrt   c           
      C  s   | j | }g }t|d D ]C\}}z| j| }W n ty2 } ztd| d|d  d|d }~ww t|tjsDJ |j d| d|	|| }	|
|	 q|S )Nrt   Input component with id 	 used in r   z() event is not defined in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events. Component with id  not a valid input component.)r   r	  r5   re   r!   rO   r   r^   rU   r   r`   )
rW   ry  rt   r   r  r  rq  r\   rT  Zserialized_inputr8   r8   r<   r  w  s*   
zBlocks.serialize_datarv   c           
      C  s   | j | }g }t|d D ]J\}}z| j| }W n ty2 } ztd| d|d  d|d }~ww t|tjsDJ |j d| d|j	|| |j
|jtjd}	||	 q|S )	Nrv   Output component with id r  r   () event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events.r   not a valid output component.)save_dirrD   hf_token)r   r	  r5   re   r!   rO   r   r^   rU   ZdeserializeZDEFAULT_TEMP_DIRrD   r   r  r`   )
rW   ry  rv   r   r   r  rr  r\   rT  Zdeserializedr8   r8   r<   r    s4   
zBlocks.deserialize_datac                 C  s   | j | }| j| }|d }t|t|k rw|jr%|jdkr%d|j dnd}g }g }|D ]}	| j|	 }
|t|
 q-|D ]}t|trKd| dnt|}|| q>d|}d|}t	d| d	t| d
t| d| d| dd S )Nrt   <lambda> ()r   ", An event handlerz- didn't receive enough input values (needed: z, got: zz).
Check if the event handler calls a Javascript function, and make sure its return value is correct.
Wanted inputs:
    [z]
Received inputs:
    [])
r   r   r   r9   r5   r`   rP   rO   joinrd   )rW   ry  rt   r|  r   Z
dep_inputsr9   wanted_argsreceived_argsrq  r\   r  vwantedreceivedr8   r8   r<   validate_inputs  s8   





zBlocks.validate_inputsr  dict[int, Any]c                 C  s   | j | }| j| }| || |jrng }t|d D ]P\}}z| j| }	W n ty@ }
 ztd| d|d  d|
d }
~
ww t|	t	j
sRJ |	j d| dt|	dd	ra||| q||	||  q|S |}|S )
Nrt   r  r  r   r  r  r  rz  F)r   r   r  rx   r	  r5   re   r!   rO   r   r7   rU   r   r`   r   )rW   ry  rt   r  r|  r   r  r  rq  r\   rT  r8   r8   r<   preprocess_data  s6   

zBlocks.preprocess_datar   Any | list[Any]c                 C  s  | j | }| j| }|d }t|turt|tur|g}t|t|k r|jr4|jdkr4d|j dnd}g }g }|D ]}	| j|	 }
|t	|
 q<|D ]}t
|t	rZd| dnt	|}|| qMd|}d|}td| d	t| d
t| d| d| dd S )Nrv   r  r  r  r   r  r  r  z. didn't receive enough output values (needed: z, received: z).
Wanted outputs:
    [z]
Received outputs:
    [r  )r   r   r   r   tupler   r9   r5   r`   rP   rO   r  rd   )rW   ry  r   r|  r   Zdep_outputsr9   r  r  rr  r\   predr  r  r  r8   r8   r<   validate_outputs  s<   





zBlocks.validate_outputsr   c                 C  s  | j | }| j| }|d }t|tu r!t|dkr!t|d |}t|d dkr.|s.|g}| || g }t|d D ]\}}	z|| tj	j
u rP|d  W q<W n ttfyh }
 z	td|j |
d }
~
ww z| j|	 }W n ty } ztd|	 d|d  d	|d }~ww t|d
drt|| s|| ||	< |d  q<|| }t|rt|tsJ t|||jd}n|jrt|tjsJ |j d|	 d||}|| q<|S )Nr   r   rv   rI   zXNumber of output components does not match number of values returned from from function r  r  r   r  rz  F)r\   r   ry   r  r  )r   r   r   r   r   r   r  r	  r   r   r  r`   
IndexErrorre   rd   r9   r5   r!   r   r   Z	is_updaterO   r   ry   r7   rU   )rW   ry  r   r  r|  r   r   outputr  rr  errr\   rT  r   r8   r8   r<   postprocess_data  sv   




zBlocks.postprocess_datarU  r   session_hashrunr   c              	   C  s   |d u s|d u r
|S || j | vri | j | |< | j | | }ddlm} t| j| d D ]>\}}| j| }	t|	|rl|	jrl||v}
|	|| | d| d| |
\}}|
r\g ||< | j | | | 	| |||< q.|S )Nr   )StreamableOutputrv   r  )
r-  gradio.eventsr  r	  r   r5   rO   Z	streamingZstream_outputr`   )rW   ry  rU  r  r  Z
stream_runr  r  rr  r\   Zfirst_chunkZbinary_dataZoutput_datar8   r8   r<   handle_streaming_outputsB  s&   
zBlocks.handle_streaming_outputsr  	iteratorsdict[int, Any] | Noner   c	                   s  j  }	j d }
|
rj d }dd |D }|d  t|	js-t|	jr1tdt fdd|D sDtd	| d
 |krStd  d| dfddt| D }	t
t| d|||I dH }|d }fddt| D }t
t| }d\}}nN|r|dnd}|rg }n|}|du}	|||||I dH }|d }|d |d }}|s|rۈj|||rt|nt|d}|	 j|d 7  _|	 jd7  _||||d |	j|	j dS )a
  
        Processes API calls from the frontend. First preprocesses the data,
        then runs the relevant function, then postprocesses the output.
        Parameters:
            fn_index: Index of function to run.
            inputs: input data received from the frontend
            state: data stored from stateful components for session (key is input block id)
            request: the gr.Request object containing information about the network request (e.g. IP address, headers, query parameters, username)
            iterators: the in-progress iterators for each generator function (key is function index)
            event_id: id of event that triggered this API call
            event_data: data associated with the event trigger itself
        Returns: None
        r   r   c                 S  s   g | ]}t |qS r8   )r   r~  r8   r8   r<   r   {  r   z&Blocks.process_api.<locals>.<listcomp>r   z1Gradio does not support generators in batch mode.c                 3  s    | ]}| kV  qd S rm   r8   )r:   r   )
batch_sizer8   r<   r!    s    z%Blocks.process_api.<locals>.<genexpr>zQAll inputs to a batch function must have the same length but instead have sizes: .zBatch size (z0) exceeds the max_batch_size for this function (r  c                      g | ]}  t|qS r8   )r  r   rc  ry  rW   r  r8   r<   r         Nr  c                   r  r8   )r  r   rf  r  r8   r<   r     r  )NNr  r  )r  r  r  rI   )rU  r  r  r  Zaverage_duration)r   r   r   r{  rr   r   rd   r   rk  r  r   r   r  r  r  rM   r   r   )rW   ry  rt   r  r  r  r  r  r  r|  r   r   Zbatch_sizesresultpredsrU  r  r  Zold_iteratorZwas_generatingr8   )r  ry  rW   r  r<   r  ^  sp   





zBlocks.process_apic                   s(   | j dkrd | _d S t| j d| _d S )Nr  )Ztotal_tokens)r,  r   r$  ra   r8   r8   r<   create_limiter  s   

zBlocks.create_limiterc                 C  s   ddiS )Nr   columnr8   ra   r8   r8   r<   r     r   zBlocks.get_configc                   s  t j| j| j| j| jg | j| jpd| jt	| ddt	| dd| j
t | j| jjd} fdd  | |d< | j D ]@\}}t|d	rH| ni }|| t|d
}t|}|rtt|tjsdJ ||d< | |d< | |d< |d | q;| j|d< |S )Nr  r+  Fr.  )r   r   rG  rD  r  r   r  r  r@  r+  r.  rH  is_colabr(  r  c                   s>   t | ts
d| jiS g }| jD ]	}| | q| j|dS )NrM   )rM   rb   )rO   r   rN   rb   r`   )r\   Zchildren_layoutr   
get_layoutr8   r<   r    s   


z*Blocks.get_config_file.<locals>.get_layoutra  r   )rM   r   r   r   r   r   r   r   )r   VERSIONr   rG  rD  r  r  r  r@  r   rH  r   colab_checkr(  r  r9   r5   r   rh   r   rk   r2   Zget_serializer_namerO   r   r  r   r   r`   r   )rW   r   rN   r\   r   r\  r   r8   r  r<   get_config_file  sB   



zBlocks.get_config_filec                 C  s(   t jd u r| t _t j| _| t _d| _| S )NF)r   r\   r[   rS   exitedra   r8   r8   r<   r     s   
zBlocks.__enter__r   r   c                   s   |d urd t _d t _d S t   | jt _|   | jd u r"d t _n| jj| j | 	 | _
tj| | _tdd | jD | _d| _d S )Nc                 s  s    | ]}|j V  qd S rm   )r   )r:   r|  r8   r8   r<   r!    s    z"Blocks.__exit__.<locals>.<genexpr>T)r   r\   r[   r9  r   rS   attach_load_eventsrb   rx  r  r   r   App
create_appappr   r   rM  r  r   rV  r8   r<   r     s   



zBlocks.__exit__Fro   rp   T)r9   srcapi_keyaliasrW   Blocks | Nonerr   rs   list[Component] | Noner}   rz   r{   r   r   rx   ry   r   r   _jsr9   r  r  r  Blocks | dict[str, Any] | Nonec                K  s   | du rt d |du rtdtjd
||||d|S ddlm} | jd|||||
|||||||	|dd	\}}|| |||S )a  
        For reverse compatibility reasons, this is both a class method and an instance
        method, the two of which, confusingly, do two completely different things.

        Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead.

        Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
        Parameters:
            name: Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
            src: Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
            api_key: Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
            alias: Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
            fn: Instance Method - the function to wrap an interface around. 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: Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
            outputs: Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
            api_name: Instance Method - 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, 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.
            scroll_to_output: Instance Method - If True, will scroll to output component on completion
            show_progress: Instance Method - If True, will show progress animation while pending
            queue: Instance Method - If True, will place the request on the queue, if the queue exists
            batch: Instance Method - 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: Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
            preprocess: Instance Method - 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: Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.
            every: Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.
        Example:
            import gradio as gr
            import datetime
            with gr.Blocks() as demo:
                def get_time():
                    return datetime.datetime.now().time()
                dt = gr.Textbox(label="Current time")
                demo.load(get_time, inputs=None, outputs=dt)
            demo.launch()
        Nz;gr.Blocks.load() will be deprecated. Use gr.load() instead.z>Blocks.load() requires passing parameters as keyword arguments)r9   r  r  r  r   )
Dependencyr  T)rq   rr   rt   rv   r|   rx   ry   rz   r{   r~   r   r   r   r   r   r8   )r   rd   r   r  r  r  r   )rW   rr   rt   rv   r|   rz   r{   r   r   r   rx   ry   r   r  r9   r  r  r  rL   r  r   Z	dep_indexr8   r8   r<   r    s@   8
zBlocks.loadc                 C  s   i | _ g | _g | _g | _| S )z'Resets the layout of the Blocks object.)r5   r   r   rb   ra   r8   r8   r<   clear_  s
   zBlocks.clearrI   autoconcurrency_countstatus_update_ratefloat | Literal['auto']client_position_to_load_datadefault_enabledr?  max_sizec                 C  s   |durt d d| _|| _|durt d t r%| j}|du r#dn|}tj|dk||dkr1|nd|| jd| _	| 
 | _tj| | _| S )a  
        By enabling the queue you can control the rate of processed requests, let users know their position in the queue, and set a limit on maximum number of events allowed.
        Parameters:
            concurrency_count: Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.
            status_update_rate: If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
            client_position_to_load_data: DEPRECATED. This parameter is deprecated and has no effect.
            default_enabled: Deprecated and has no effect.
            api_open: If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
            max_size: The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
        Example: (Blocks)
            with gr.Blocks() as demo:
                button = gr.Button(label="Generate Image")
                button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
            demo.queue(max_size=10)
            demo.launch()
        Example: (Interface)
            demo = gr.Interface(image_generator, gr.Textbox(), gr.Image())
            demo.queue(max_size=20)
            demo.launch()
        NzgThe default_enabled parameter of queue has no effect and will be removed in a future version of gradio.Tz9The client_position_to_load_data parameter is deprecated.rI   r  )Zlive_updatesr  Zupdate_intervalsr  Zblocks_dependencies)r   r+  r?  r   Zis_zero_gpu_spacer,  r   Queuer   _queuer  r   r   r  r  r  )rW   r  r  r  r  r?  r  r8   r8   r<   r   g  s.   
zBlocks.queuec                 C  s   | j s
| jr
tdt| jD ]C\}}| j s+| |r+td|d r%|d n| d|d D ]}| |s:tdq/|d rR|d d	u sN|d d u rR| j sRtd
qd S )Nz1Progress tracking requires queuing to be enabled.zThe queue is enabled for event r|   z but the queue has not been enabled for the app. Please call .queue() on your app. Consult https://gradio.app/docs/#blocks-queue for information on how to configure the queue.r   a!  Queue needs to be enabled! You may get this error by either 1) passing a function that uses the yield keyword into an interface without enabling the queue or 2) defining an event that cancels another event without enabling the queue. Both can be solved by calling .queue() before .launch()r   r   Fz4In order to use batching, the queue must be enabled.)r+  rM  rd   r	  r   queue_enabled_for_fn)rW   ry  r   r  r8   r8   r<   validate_queue_settings  s&   
zBlocks.validate_queue_settingsr    100%inline	inbrowserr*  debugr+  r,  rB  9Callable | tuple[str, str] | list[tuple[str, str]] | Noneauth_messageprevent_thread_lockr.  server_nameserver_port	show_tipsr>  r=  	int | strr)  rA  ssl_keyfilessl_certfilessl_keyfile_passwordrN  quietrH  file_directorieslist[str] | NonerO  rP  rQ  	_frontend
app_kwargsdict[str, Any] | Nonetuple[FastAPI, str, str]c           *      C  s  | j rdS | js|   |r%t|s%t|d ts%t|d ts%|g| _n|| _|| _|| _	|
| _
|| _|| _|| _|| _|du rJtjdd| _n|| _|durX|| _td |dur`td | jrj| jdu| _n| jd	u | _| jr|t| d
s||   || _|durtd |du r|}|pg | _|pg | _t| jtstdt| jtstd|   |  | _t| jr| j j!nd|| _"| j#rt| j$t%sJ d| j$ |st&d nt'j(rd}d}d}d}ddl)m*}  | j+| |d}!t',|! nt-j.| ||||||d\}}}}!}|| _/|| _$|| _0|!| _1|| _2d	| _#t34 | _5t36 | _7| j$8ds/| j5r1dnd| _9t'j(sK| j5sKt&t:j;d <| j9| j/| j0 | jrV| j =| j1 t'j(sft>j| j$ d|d n	 t3?  t3@ | _A|du r| j5r| jr|st&d d	| _Bn%| j7r|st&d d	| _Bn| jAr|st&d d	| _Bnd| _Bn|| _B|rt'j(st-C| j$s| jBstd| j5r|s|rt&t:j;d  nt&t:j;d  | jBst&t:j;d <| j0 | jr| jBstd | jBrm| jrtDd!t'j(rtDd"z(| jEdu rt-F| j/| j0| jG| _Et&t:j;d# <| jE |s2t&t:j;d$  W nJ tDt>jHjIfyl   | jJrHtKLd% d| _Ed| _BtMtNO r]t&t:j;d&  nt&t:j;d' <tNtPtQtR Y nw |s{t'j(s{t&t:j;d(  d| _E|rt'j(s| jBr| jEr| jEn| j$}"tST|" |du rt3U }|r'zxdd)lVmW}#mX}$mY}% | jBr| jErt-C| jEstZ[d* t-C| jEr|#d+| jE d,| j d-| j d.}&n8| j5rd/d0j<t\]| j0t\]d1t\]| jt\]| jt\]dd2 }'|$|'}&n|#d+| j$ d,| j d-| j d.}&|&| _^|%|& W n
 t_y&   Y nw t`| d3drO|r3d4nd5| j5| jB| jE| j| j	||| jdu| jad6
}(tKb| |( t3c|  |sftdted7dd8krjt'j(sj| f  tgt`thd9thjijj})|	s|)st'j(s| f  tk| j1| j$| jEfS ):a  
        Launches a simple web server that serves the demo. Can also be used to create a
        public link used by anyone to access the demo from their browser by setting share=True.

        Parameters:
            inline: whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
            inbrowser: whether to automatically launch the interface in a new tab on the default browser.
            share: whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
            debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
            auth: If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.
            auth_message: If provided, HTML message provided on login page.
            prevent_thread_lock: If True, the interface will block the main thread while the server is running.
            show_error: If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
            server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
            server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
            show_tips: if True, will occasionally show tips about new Gradio features
            enable_queue: DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
            max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.
            width: The width in pixels of the iframe element containing the interface (used if inline=True)
            height: The height in pixels of the iframe element containing the interface (used if inline=True)
            encrypt: DEPRECATED. Has no effect.
            favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
            ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
            ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
            ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
            ssl_verify: If False, skips certificate validation which allows self-signed certificates to be used.
            quiet: If True, suppresses most print statements.
            show_api: If True, shows the api docs in the footer of the app. Default True.
            file_directories: This parameter has been renamed to `allowed_paths`. It will be removed in a future version.
            allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
            blocked_paths: List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
            root_path: The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". Can be set by environment variable GRADIO_ROOT_PATH. Defaults to "".
            app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
        Returns:
            app: FastAPI app object that is running the demo
            local_url: Locally accessible link to the demo
            share_url: Publicly accessible link to the demo (if share=True, otherwise None)
        Example: (Blocks)
            import gradio as gr
            def reverse(text):
                return text[::-1]
            with gr.Blocks() as demo:
                button = gr.Button(value="Reverse")
                button.click(reverse, gr.Textbox(), gr.Textbox())
            demo.launch(share=True, auth=("username", "password"))
        Example:  (Interface)
            import gradio as gr
            def reverse(text):
                return text[::-1]
            demo = gr.Interface(reverse, "text", "text")
            demo.launch(share=True, auth=("username", "password"))
        r   r   Nr  r   z[The `enable_queue` parameter has been deprecated. Please use the `.queue()` method instead.z>The `encrypt` parameter has been deprecated and has no effect.FTr  z^The `file_directories` parameter has been renamed to `allowed_paths`. Please use that instead.z.`allowed_paths` must be a list of directories.z.`blocked_paths` must be a list of directories.zInvalid local_url: z[Rerunning server... use `close()` to stop if you need to change `launch()` parameters.
----Zxxxi )r  )r   httpshttpZRUNNING_LOCALLY_SEPARATEDzstartup-events)verifyzSetting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
zKaggle notebooks require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
zSagemaker notebooks may require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
zWhen localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost.ZCOLAB_DEBUG_TRUEZCOLAB_DEBUG_FALSEZCOLAB_WARNINGzVWhen using queueing in Colab, a shareable link must be created. Please set share=True.z-Share is not supported when you are in Spacesz.Share is not supported in the Wasm environmentZSHARE_LINK_DISPLAYZSHARE_LINK_MESSAGEzNot able to set up tunnelZCOULD_NOT_GET_SHARE_LINKZ%COULD_NOT_GET_SHARE_LINK_MISSING_FILEZPUBLIC_SHARE_TRUE)HTML
Javascriptdisplayg      ?z<div><iframe src="	" width="
" height="zx" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>aW  (async (port, path, width, height, cache, element) => {
                        if (!google.colab.kernel.accessAllowed && !cache) {
                            return;
                        }
                        element.appendChild(document.createTextNode(''));
                        const url = await google.colab.kernel.proxyPort(port, {cache});

                        const external_link = document.createElement('div');
                        external_link.innerHTML = `
                            <div style="font-family: monospace; margin-bottom: 0.5rem">
                                Running on <a href=${new URL(path, url).toString()} target="_blank">
                                    https://localhost:${port}${path}
                                </a>
                            </div>
                        `;
                        element.appendChild(external_link);

                        const iframe = document.createElement('iframe');
                        iframe.src = new URL(path, url).toString();
                        iframe.height = height;
                        iframe.allow = "autoplay; camera; microphone; clipboard-read; clipboard-write;"
                        iframe.width = width;
                        iframe.style.border = 0;
                        element.appendChild(iframe);
                    })z<({port}, {path}, {width}, {height}, {cache}, window.element)r  )portr0  r=  r>  cacher  Zbrowserr  )
Zlaunch_methodZis_google_colabZis_sharing_onr<  r+  r  r  r  Zis_spacer   ZGRADIO_DEBUGrI   ps1)lrX  r  r   callablerO   r  r   rB  r  r  r.  r>  r=  rA  rN  r/  r8  r   rQ  r+  r   r@  rh   r   rH  rO  rP  rd   r  r  r   maxr  Zmax_thread_countr,  r:  r;  rP   printr   r4  Zgradio.routesr  r  Zregister_appr   start_serverr  r  Z
server_appserverr   r  r  Zkaggle_checkZ	is_kaggle
startswithprotocolr   enformatZset_server_appr  Zlaunch_counterZsagemaker_checkZis_sagemakerr*  Zurl_okRuntimeErrorr<  Zsetup_tunnelrR   
exceptionsConnectionErrorr  r   Zerror_analyticsr   r*   r1  r+   r(   r)   
webbrowserr2  Zipython_checkIPython.displayr  r  r  r  sleepjsondumpsartifactImportErrorr   r   Zlaunched_analyticsZshow_tipr   rC  block_threadrF   sysflagsr   r.   )*rW   r  r  r*  r  r+  r,  rB  r  r  r.  r  r  r  r>  r=  r)  rA  r  r  r  rN  r  rH  r  rO  rP  rQ  r  r   r;  r  r  r  linkr  r  r  r  coderU  Zis_in_interactive_moder8   r8   r<   r    s  T





















 
$zBlocks.launchwandbModuleType | NonemlflowNonec                 C  s"  d}|dur6d}| dd | jdur!|d| j  |  n| jr2|d| j  |  ntd|durcd}| jdur_|d	|d
| j d t| j	 d t| j
 d i ntd |dur}d}| jdurv|d| j n|d| j | jr|rd|i}t| dS dS dS )a  
        A catch-all method for integrating with other libraries. This method should be run after launch()
        Parameters:
            comet_ml: If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
            wandb: If the wandb module is provided, will integrate with it and appear on WandB dashboard
            mlflow: If the mlflow module  is provided, will integrate with the experiment and appear on ML Flow dashboard
        r   NZCometMLzCreated fromr  zgradio: zPlease run `launch()` first.ZWandBzGradio panelz<iframe src="r	  r
  z" frameBorder="0"></iframe>zAThe WandB integration requires you to `launch(share=True)` first.ZMLFlowzGradio Interface Share LinkzGradio Interface Local LinkZintegration)Z	log_otherr<  Zlog_textendr;  rd   logZHtmlrP   r=  r>  r  Z	log_paramr  r   Zintegration_analytics)rW   Zcomet_mlr&  r(  Zanalytics_integrationrU  r8   r8   r<   r  Q  sX   





zBlocks.integrateverbosec              	   C  sh   z'| j r	| j  | jr| j  d| _d| j_|r%td| j  W dS W dS  t	t
fy3   Y dS w )zL
        Closes the Interface that was launched and frees the port.
        Fz Closing server running on port: N)r+  r  closer  r:  r  Zstartup_events_triggeredr  r  r   OSError)rW   r,  r8   r8   r<   r-    s   

zBlocks.closec              	   C  sR   z	 t d q ttfy(   td | jr| j  tD ]}|  qY dS w )z,Block main thread until interrupted by user.Tg?z7Keyboard interruption in main thread... closing server.N)	r  r  KeyboardInterruptr.  r  r  r-  r,   kill)rW   Ztunnelr8   r8   r<   r!    s   


zBlocks.block_threadc              
   C  sj   t jr1t jj D ])}t|tjr0|jr0|j\}}| jd|d|d|du r&dnd|dd }||_	q	dS dS )zNAdd a load event for every component whose initial value should be randomized.r  NTF)r   r   r   r   )
r   r[   r5   rS  rO   r   r^   Zload_event_to_attachr   Z
load_event)rW   r   Zload_fnr   r   r8   r8   r<   r    s,   

zBlocks.attach_load_eventsc                 C  s0   | j rt| jj| j d| j_t| j dS )zGEvents that should be run when the app containing this block starts up.FN)r+  r   Zrun_coro_in_backgroundr  r7  rN  stoppedr  ra   r8   r8   r<   startup_events  s   zBlocks.startup_eventsc                 C  s&   | j | d d u r| jS | j | d S )Nr   )r   r+  )rW   ry  r8   r8   r<   r    s   zBlocks.queue_enabled_for_fn)NNr5   r  N)
r  r  r  r   r   rP   r  rP   r  rG   )r   r   r   rY  rD   rP   rg   r  r  )ry  r   rg   rF   )ry  r   r|   rG   )NNNN)ry  r   r  r  r  r  r  r  r  rG   r  r  )ry  r   rt   r  rg   r  )ry  r   rv   r  rg   r  )ry  r   rt   r  )ry  r   rt   r  r  r  )ry  r   r   r  )ry  r   r   r   r  r  )
ry  r   rU  r   r  rG   r  r   rg   r   )NNNNN)ry  r   rt   r  r  r  r  r  r  r  r  rG   r  rG   r  r  rg   r   rm   r   )NNNNNFro   NFrp   TTNN)$rW   r  rr   rs   rt   r  rv   r  r|   r}   rz   rF   r{   rP   r   rF   r   r   rx   rF   ry   rF   r   r   r  rG   r9   rG   r  rG   r  rG   r  rG   rg   r  )rI   r  NNTN)r  r   r  r  r  r   r  r   r?  rF   r  r   )NFNFNr  NNFFNNFr  r  NNNNNTFTNNNNTN)<r  r   r  rF   r*  r   r  rF   r+  r   r,  r   rB  r  r  rG   r  rF   r.  rF   r  rG   r  r   r  rF   r>  r   r=  r  r)  r   rA  rG   r  rG   r  rG   r  rG   rN  rF   r  rF   rH  rF   r  r  rO  r  rP  r  rQ  rG   r  rF   r   r  rg   r  r   )r&  r'  r(  r'  rg   r)  T)r,  rF   rg   r)  )rg   r)  )ry  r   )+rV   r   r   __doc__rX   propertyrX  r   rm  r   r   rs  r@   r}  r  r  r  r  r  r  r  r  r  r  r  r   r  r   r   r  r  r1   r   r   r  r  r  r-  r!  r  r2  r  __classcell__r8   r8   rV  r<   r  x  s    $n
v
;9
P


&

$
<!V.Y6   8
	r  r3  )r\   r?   r   r   ry   rF   )r   r   r   r   rg   r   )r   r   r   rF   )g
__future__r   r   r   r  r/  rE  rQ   r"  r5  r  r   r  abcr   collectionsr   pathlibr   r   r   typingr   r   r	   r
   r   r   r  r  r   Zgradio_clientr   r   r
  Zgradio_client.documentationr   r   	packagingr   Zgradior   r   r   r   r   r   r   r   r   Zgradio.contextr   Zgradio.deprecationr   r   Zgradio.exceptionsr   r    r!   Zgradio.helpersr"   r#   r$   r%   Zgradio.themesr&   r%  r'   r&  Zgradio.tunnelingr(   r)   r*   r+   r,   Zgradio.utilsr-   r.   r/   r0   r1   r2   r3   r4   r   r'  Zfastapi.applicationsr6   Zgradio.componentsr7   ZBaseZ
MonochromeZSoftZGlassr>   __annotations__r?   r   r   r   r   r  r  r8   r8   r8   r<   <module>   sx     0( o@+
 