
    ;3hxB             	         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Zd dlZd dlZd dlZd dlZd dlmZ d dlmZmZmZmZmZ d dlmZ d dlmZ d dlmZm Z m!Z!m"Z"m#Z# d dl$m%Z%m&Z& d dl'Z'd dl(Z(d dl)Z)d d	l'm*Z* d d
l+m,Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m,Z,m9Z9 d dl:m;Z;m<Z<m=Z= d dl>m?Z?m@Z@mAZAmBZBmCZC d dlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZL d dlMmNZNmOZOmPZP d dlQmRZRmSZSmTZTmUZU d dlVmWZWmXZXmYZY d dlZm[Z[m\Z\ d dl]m^Z^ d dl_m`Z`maZa d dlbmcZcmdZdmeZemfZf d dlgmhZhmiZi d dljmkZl d dljmmZn d dlompZpmqZqmrZrmsZsmtZt d dlumvZvmwZwmxZxmyZymzZzm{Z{m|Z| 	 d dl}Z}erd dlmZ d dlmZ  e8j                          e8j                          e8j                          e8j
                          e8j                          e8j                          e8j                          e8j                         fD  ci c]  } | j                  |  c} Zded <    G d! d"      Z G d# d$e      Z G d% d&      Z	 d3	 	 	 	 	 d4d'Z	 	 	 	 	 	 d5d(Z G d) d*      Z e/d+d,d-d.d/       G d0 d1ee<e=2             Zy# e~$ r dZ}Y w xY wc c} w )6    )annotationsN)defaultdict)AsyncIteratorCallable	CoroutineSequenceSet)Path)
ModuleType)TYPE_CHECKINGAnyLiteralUnioncast)urlparse
urlunparse)CapacityLimiter)utils)document)	transpile)	analytics
components
networkingprocessing_utilsqueueingthemesr   
wasm_utils)BLOCKS_EVENTSBlocksEvents
BlocksMeta)ContextLocalContextget_blocks_contextget_render_contextset_render_context)APIEndpointInfoAPIInfoBlocksConfigDictDeveloperPathFileDataGradioModelGradioRootModelLayout)	EventDataEventListenerEventListenerMethod)ChecksumMismatchErrorDuplicateBlockErrorInvalidApiNameErrorInvalidComponentError)create_trackerskipspecial_args)I18nI18nData)start_node_server)
API_PREFIXMediaStream)INTERNAL_ROUTESVERSIONAppRequest)SessionStateStateHolder)Default)
ThemeClass)BINARY_FILENAMEBINARY_FOLDERBINARY_PATH
BINARY_URLCURRENT_TUNNELS)TupleNoPrintcheck_function_inputs_matchcomponent_or_layout_classget_cancelled_fn_indicesget_node_pathget_package_versionget_upload_folder)	Component)
Renderablezdict[str, Theme]BUILT_IN_THEMESc                  
   e Zd Zdddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZedd       Zedd       Zedd	       Ze	 	 dd
       Z	d Z
d ZddZddZddZd Ze	 d	 	 	 dd       Z	 	 	 	 ddZ	 	 	 	 ddZ	 	 	 	 ddZy) BlockNTvalue)elem_idelem_classesrenderkeypreserved_by_keyvisible	proxy_urlc                  t         j                  j                         }||r||v rd| _        ||   | _        nHd| _        t
        j                  | _        t
        xj                  dz  c_        ||| j                  ||<   || _        || _        t        |t              r|gn|| _        || _        t        j                  d      | _        d | _        d | _        |  d| _        |  d| _        t)               | _        t-               | _        || _        t        |t              r|gn|xs g | _        t)               | _        d| _        |r| j9                          y y )NTF       '  )r"   key_to_id_mapgetis_render_replacement_idr!   idr\   rW   
isinstancestrrX   r]   secretstoken_urlsafeshare_tokenparentrendered_inis_renderedstate_session_capacityset
temp_filesrP   GRADIO_CACHErZ   r[   keep_in_cachehas_launchedrY   )	selfrW   rX   rY   rZ   r[   r\   r]   rb   s	            M/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/blocks.py__init__zBlock.__init__|   s>    %22668?}1E)-D&$S)DH).D&zzDHJJ!OJ=#<%)XXc"(s;\N 	 #"004+/.2!&&+#$'E-/ *C0 "(b 	 !U!KKM     c                    | j                   y t        | j                  r| j                  j                  nd | j                   f      S N)rZ   hashrm   re   ru   s    rv   
unique_keyzBlock.unique_key   s9    88T-=-=T%%))4RSSrx   c                     yNF r|   s    rv   statefulzBlock.stateful       rx   c                     yr   r   r|   s    rv   skip_apizBlock.skip_api   r   rx   c                <    | j                   r| j                   d   S i S )z|Get the arguments passed to the component's initializer.

        Only set classes whose metaclass is ComponentMeta
        r   )_constructor_argsr|   s    rv   constructor_argszBlock.constructor_args   s"     -1,B,Bt%%a(JJrx   c                    t        | dg       S )NEVENTS)getattrr|   s    rv   eventszBlock.events   s     tXr**rx   c                6   t               }t               }t        j                  j	                         | _        |=| j                  |j                  v r%| j                  st        d| j                   d      |5|r|j                  j                  | _        |j                  |        || _        |i| |j                  | j                  <   d| _        t!        | t"        j$                        r/|j                  j&                  j)                  | j*                         | S )z9
        Adds self into appropriate BlockContext
        A block with id: 1 has already been rendered in the current Blocks.T)r#   r$   r"   
renderablerc   rm   re   blocksrd   r2   
root_blockcurrent_pagepageaddrl   rn   rg   r   rQ   temp_file_setsappendrq   )ru   root_contextrender_contexts      rv   rY   zBlock.render   s     *++-'22668$L///..%#DHH:-^_  %(33@@	t$(DK#,0L)#D$
 4 45''66==dooNrx   c                (   t               }t        | d      r9| j                  -	 | j                  j                  j	                  |        d| _        |!	 |j                  | j                  = d| _        | S | S # t
        $ r Y 0w xY w# t        $ r Y | S w xY w)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.
        rl   NF)
r#   hasattrrl   childrenremove
ValueErrorr   re   rn   KeyError)ru   r   s     rv   unrenderzBlock.unrender   s    
 *+4"t{{'>$$++D1" # ''1#(  t    s#   ,A5 B 5	B B	BBc                    t        | d      r.| j                  j                  j                  j	                         S | j                  j                  j	                         S )a#  
        Gets block's class name. If it is template component it gets the parent's class name.
        This is used to identify the Svelte file to use in the frontend. Override this method
        if a component should use a different Svelte file than the default naming convention.
        is_templater   	__class____base____name__lowerr|   s    rv   get_block_namezBlock.get_block_name   sN     t]+ NN##,,224	
 ((..0	
rx   c                    t        | d      r.| j                  j                  j                  j	                         S | j                  j                  j	                         S )a4  
        Gets block's class name. If it is template component it gets the parent's class name.
        Very similar to the get_block_name method, but this method is used to reconstruct a
        Gradio app that is loaded from a Space using gr.load(). This should generally
        NOT be overridden.
        r   r   r|   s    rv   get_block_classzBlock.get_block_class  sN     t]+ NN##,,224	
 ((..0	
rx   c                     y rz   r   r|   s    rv   get_expected_parentzBlock.get_expected_parent  s    rx   c                X   i }t        j                  | j                  j                        }|j                  j                         D ]h  }t        | |j                        st        | |j                        }t        j                  |      rt        j                  |      }|||j                  <   j | j                  D ]  }|j                         }|si ||} |j                  dd        i || j                  | j!                         d}dD ]  }t        | |d       x}|||<    |S )NrY   )r]   name)_selectable	_undoable
_retryablelikeable)inspect	signaturer   rw   
parametersvaluesr   r   r   dataclassesis_dataclassasdictr   config_datapopr]   r   )	ru   configr   	parameterrV   eto_addevent_attributeattributables	            rv   
get_configzBlock.get_config  s   %%dnn&=&=>	"--446 	/ItY^^,inn5++E2'..u5E).y~~&	/  	.A]]_F-F-f-	. 	

8T"XFXAUAUAWXU 	7O 'ot DDQ*6'	7 rx   c                   |xs g }t        j                  | j                        }i }|j                  j	                         D ]<  }|j
                  |v s|j
                  |vs!||j
                     ||j
                  <   > |S )z7
        Recovers kwargs from a dict of props.
        )r   r   rw   r   r   r   )clspropsadditional_keysr   kwargsr   s         rv   recover_kwargszBlock.recover_kwargs+  sz     */R%%cll3	"--446 	?I~~&9>>+P).y~~)>y~~&	? rx   c                "  K   |yt        |t              rt        |      }t        j                  |      rFt        j                  || j                         d{   }| j                  j                  |       |S t        t        j                  |            }t        j                  || j                        s#	 t        j                  || j                        }n|}| j                  j                  |       |S 7 # t        $ r |cY S w xY ww)a  Moves a file or downloads a file from a url to a block's cache directory, adds
        to to the block's temp_files, and returns the path to the file in cache. This
        ensures that the file is accessible to the Block and can be served to users.

        This async version of the function is used when this is being called within
        a FastAPI route, as this is not blocking.
        N	cache_dir)rg   r
   rh   client_utilsis_http_url_liker   async_ssrf_protected_downloadrr   rq   r   r   abspathis_in_or_equalsave_file_to_cacheFileNotFoundErrorru   url_or_file_pathtemp_file_paths      rv   "async_move_resource_to_block_cachez(Block.async_move_resource_to_block_cache:  s      #&-"#34(()9:#3#Q#Q D,=,=$ N OO/$ !  #5==1A#BC''(8$:K:KL	,%5%H%H(D4E4E&N "2OO/- ) ,
 ,+,s7   ADC<AD;!C> !D>D	DDDc                   |yt        |t              rt        |      }t        j                  |      r>t        j                  || j                        }| j                  j                  |       |S t        t        j                  |            }t        j                  || j                        s#	 t        j                  || j                        }n|}| j                  j                  |       |S # t        $ r |cY S w xY w)a  Moves a file or downloads a file from a url to a block's cache directory, adds
        to to the block's temp_files, and returns the path to the file in cache. This
        ensures that the file is accessible to the Block and can be served to users.

        This sync version of the function is used when this is being called outside of
        a FastAPI route, e.g. when examples are being cached.
        Nr   )rg   r
   rh   r   r   r   save_url_to_cacherr   rq   r   r   r   r   r   r   r   s      rv   move_resource_to_block_cachez"Block.move_resource_to_block_cacheb  s     #&-"#34(()9:-?? D,=,=N OO/$ !  #5==1A#BC''(8$:K:KL	,%5%H%H(D4E4E&N "2OO/ ) ,
 ,+,s   1!C2 2D ?D c                    |yt        |t              r|S t        |t              rt        |      }t	        j
                  |      rt        ||      j                         S |ddid}	 t        j                  ||       S # t        $ r |cY S w xY w)a  If a file is a local file, moves it to the block's cache directory and returns
        a FileData-type dictionary corresponding to the file. If the file is a URL, returns a
        FileData-type dictionary corresponding to the URL. This ensures that the file is
        accessible in the frontend and can be served to users.

        Examples:
        >>> block.serve_static_file("https://gradio.app/logo.png") -> {"path": "https://gradio.app/logo.png", "url": "https://gradio.app/logo.png"}
        >>> block.serve_static_file("logo.png") -> {"path": "logo.png", "url": "/file=logo.png"}
        >>> block.serve_static_file({"path": "logo.png", "url": "/file=logo.png"}) -> {"path": "logo.png", "url": "/file=logo.png"}
        N)pathurl_typezgradio.FileData)r   meta)rg   dictr
   rh   r   r   r*   
model_dumpr   move_files_to_cacheAttributeError)ru   r   datas      rv   serve_static_filezBlock.serve_static_file  s     #&-##&-"#34(()9:!17GHSSUU,w@Q6RSD';;D$GG! s   )A? ?BB)rW   
str | NonerX   list[str] | str | NonerY   boolrZ   (int | str | tuple[int | str, ...] | Noner[   r   r\   r   r]   r   )return
int | None)r   r   )r   dict[str, Any])r   zlist[EventListener]r   rh   )r   ztype[BlockContext] | Nonerz   )r   r   r   list[str] | None)r   str | Path | Noner   r   )r   zstr | Path | dict | Noner   zdict | None)r   
__module____qualname__rw   r}   propertyr   r   r   r   rY   r   r   r   r   r   classmethodr   r   r   r   r   rx   rv   rU   rU   {   sK    #/38<3: $1 1 -	1
 1 61 11 1 1fT
     K K +	+ +
6(


( HL"5E & 1&	&P& 1&	&P 8	rx   rU   c                      e Zd Z	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ ed      ZdZed        Ze	dd       Z
ed        ZddZd	 Zdd
Zd ZdddZd Zy)BlockContextNc           	     J    g | _         t        j                  | ||||||       y)a,  
        Parameters:
            elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
            elem_classes: An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.
            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.
        )rW   rX   r\   rY   rZ   r[   N)r   rU   rw   )ru   rW   rX   r\   rY   rZ   r[   s          rv   rw   zBlockContext.__init__  s1      &(%- 	 	
rx   z./templates/z../../frontend/c                     y)NTr   r|   s    rv   r   zBlockContext.skip_api  s    rx   c                    | j                   }t        j                  |   j                  }t	        j
                  | j                   d| j                               j                         }|S )N_)	r   sysmodules__file__hashlibsha256r   encode	hexdigest)r   module_namemodule_pathmodule_hashs       rv   get_component_class_idz#BlockContext.get_component_class_id  sZ    nnkk+.77nn||nAk]+224

)+ 	 rx   c                "    | j                         S rz   )r  r|   s    rv   component_class_idzBlockContext.component_class_id  s    **,,rx   c                :    | j                   j                  |       y rz   )r   r   ru   childs     rv   	add_childzBlockContext.add_child  s    U#rx   c                >    t               }|| _        t        |        | S rz   )r$   rl   r%   ru   r   s     rv   	__enter__zBlockContext.__enter__  s    +-$4 rx   c                H    | |_         | j                  j                  |       y rz   )rl   r   r   r  s     rv   r   zBlockContext.add  s    U#rx   c                   t               }g }d }| j                  D ]  }|j                         }|rt        | |      rd }|j	                  |       5|t        ||      r|j                  |       n^ |d      }| |_        |j	                  |       |j                  |       |j                  |_        |r||j                  |j                  <   ||_         || _        y )NF)rY   )
r#   r   r   rg   r   r  rl   r   r   re   )ru   r   r   pseudo_parentr  expected_parents         rv   fill_expected_parentsz"BlockContext.fill_expected_parents  s    )+]] 	-E#779O"j&G $& ,!?2 "++E2$35$AM+/M(OOM2!++E2).M&#AN++M,=,=>,%	-& !rx   c                p    t        | j                         |y t        | dd      r| j                          y y )Nallow_expected_parentsT)r%   rl   r   r  )ru   exc_typeargss      rv   __exit__zBlockContext.__exit__  s5    4;;'4148&&( 9rx   c                    |S )zO
        Any postprocessing needed to be performed on a block context.
        r   )ru   ys     rv   postprocesszBlockContext.postprocess  s	     rx   )NNTTNN)rW   r   rX   r   r\   r   rY   r   rZ   r   r[   r   r   )r  rU   rz   r  ztype[BaseException] | None)r   r   r   rw   r)   TEMPLATE_DIRFRONTEND_DIRr   r   r   r  r  r  r  r   r  r  r  r   rx   rv   r   r     s     #/38<37

 -
 	

 
 6
 1
6 !0L$L    - -$$!2)rx   r   c                      e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd Zd Zd Zd Zy)	BlockFunctionNc$                `   || _         || _        || _        || _        || _        || _        || _        || _        |xs t        t        |            | _
        |	| _        |
| _        d| _        d| _        || _        || _        |t#        |dd      nd | _        || _        || _        || _        || _        |xs g | _        || _        || _        || _        || _        |dn|| _        t;        j<                         rdn|| _        || _         tC        jD                  | j                         xs tC        jF                  | j                         | _$        || _%        || _&        |"| _'        |#r|#| j                   _(        || _)        || _*        || _+        || _,        | | _-        |!| _.        | j_                          y )Nr   r   fnF)0r  re   inputsoutputs
preprocessr  tracks_progressconcurrency_limitrh   rf   concurrency_idbatchmax_batch_sizetotal_runtime
total_runsinputs_as_dicttargetsr   r   api_namejsshow_progressshow_progress_oncancelscollects_event_datatrigger_aftertrigger_only_on_successtrigger_modequeuer   	get_spacescroll_to_outputshow_apir   isgeneratorfunctionisasyncgenfunctiontypes_generatorr   rm   r   __js_implementation__is_cancel_function
time_limitstream_every
connectionlike_user_messageevent_specific_argsspaces_auto_wrap)$ru   r  r   r!  r"  r  r*  r+  re   r&  r'  r$  r%  r#  r,  r-  r.  r/  r0  r1  r2  r3  r4  r5  r7  r8  r   rm   r=  r@  r>  r?  rA  rB  r   js_implementations$                                       rv   rw   zBlockFunction.__init__  s   L $&.BS,;BrF
,,57^GB
D1	 * 0}"#6 *'>$( jUe
).):@P &::GG 
  1''0 	 %&	,=DGG) #5$($!2#6 rx   c                    t         y t        j                         y t        j                  | j                        | _        y rz   )spacesr   r6  gradio_auto_wrapr  r|   s    rv   rC  zBlockFunction.spaces_auto_wrapb  s0    >??$))$''2rx   c                \    t        | j                  | j                  | j                  d      S )N)r  r"  r  )rh   r   r"  r  r|   s    rv   __str__zBlockFunction.__str__i  s+    ii"oo#//
 	
rx   c                    t        |       S rz   )rh   r|   s    rv   __repr__zBlockFunction.__repr__r  s    4yrx   c                   i d| j                   d| j                  d| j                  D cg c]  }|j                    c}d| j                  D cg c]  }|j                    c}d| j                  d ud| j
                  d| j                  d| j                  d	| j                  d
| j                  d| j                  d n#| j                  D cg c]  }|j                    c}d| j                  d| j                  d| j                  d| j                  | j                  dd| j                   d| j"                  | j$                  | j&                  | j(                  | j*                  r| j*                  j                   nd | j,                  r| j,                  j                   nd | j.                  | j0                  | j2                  | j4                  | j6                  t9        | j                  dd       dS c c}w c c}w c c}w )Nrf   r+  r   r!  
backend_fnr-  r5  r,  r7  r.  r/  r&  r'  r0  types)	generatorcancelr1  r2  r<  )r3  r4  r8  rm   	render_idr@  r>  r?  rA  rB  rD  )re   r+  r   r!  r  r-  r5  r,  r7  r.  r/  r&  r'  r0  r;  r=  r1  r2  r3  r4  r8  rm   r   r@  r>  r?  rA  rB  r   )ru   blocks     rv   r   zBlockFunction.get_configu  s   "
$(("
t||"
 dkk:Uuyy:"
 t||<e		<	"

 $''-"
 $''"
 TZZ"
 "
  5 5"
 T//"
 $$, !%)-)>)>?%))?"
 TZZ"
 d11"
  t||!"
" !1111#"
* "4#;#;+"
, T//-"
. (,'C'C --373C3C4++//04,,T//// --!%!7!7#'#;#;!(2I4!PC"
 "	
 ;< @s   G<HH)F   defaultNFFNfullNNFNFonceTFTNNFsseN      ?FN N)Fr  Callable | Noner   "Sequence[Component | BlockContext]r!  r[  r"  r   r  r   r*  r   r+  zlist[tuple[int | None, str]]re   intr&  r   r'  r\  r$  int | None | Literal['default']r%  r   r#  r   r,  zstr | Literal[False]r-  str | Literal[True] | Noner.  $Literal['full', 'minimal', 'hidden']r/  zSequence[Component] | Noner0  list[int] | Noner1  r   r2  r   r3  r   r4  z*Literal['always_last', 'once', 'multiple']r5  r   r7  r   r8  r   r   Renderable | Nonerm   ra  r=  r   r@  Literal['stream', 'sse']r>  float | Noner?  floatrA  r   rB  r   r   rh   rD  r   )r   r   r   rw   rC  rI  rK  r   r   rx   rv   r  r    s    =F%) %).)->D7;$($)$((-CI!&(,)-#(/4#'!"'04(,IT T  3T  4	T 
 T  T  T  .T  T  T  T  ;T  #T  T  'T   '!T " <#T $ 5%T & "'T ( ")T * "+T , "&-T . A/T 0 1T 2 3T 4 5T 6 &7T 8 '9T : !;T < -=T > !?T @ AT B  CT D .ET F GT H &IT l3
#
rx   r  c                   |j                  dt        j                  j                        }|D ci c]  }t	        | |      s|t        | |       }}|t        j                  j                  urK|rD| j                  |      |d<   t        |d   t        t        f      r|d   j                         |d<   n||d<   d|d<   |S c c}w )a  
    Converts a dictionary of updates into a format that can be sent to the frontend to update the component.
    E.g. {"value": "2", "visible": True, "invalid_arg": "hello"}
    Into -> {"__type__": "update", "value": 2.0, "visible": True}
    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.
    rV   update__type__)r   r   	_KeywordsNO_VALUEr   r   r  rg   r+   r,   r   )rR  update_dictr  rV   ks        rv   postprocess_update_dictrl    s     OOGZ%9%9%B%BCE1<RAq@Q1geQ''RKRJ((111#(#4#4U#;K +g.o0NO'27';'F'F'HG$#(K &K
 Ss   C C c                   |D cg c]  }t        |t               }}t        |      r| D cg c]  }t                }}|j	                         D ]B  \  }}|j
                  | vrt        d| d      | j                  |j
                        }|||<   D t        j                  |      }|S t        |      rt        d      |S c c}w c c}w )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"}]
    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.)rg   rU   allr6   itemsre   r   indexr   resolve_singletonany)	outputs_idspredictionsrZ   keys_are_blocksr   reordered_predictions	componentrV   output_indexs	            rv   convert_component_dict_to_listry    s     :EE#z#u-EOE
?1< =A = = + 1 1 3 	8Iu}}K/ ))4YZ  ',,Y]];L27!,/	8 --.CD
 	 
_	 @
 	
  F =s
   CC	c                     e Zd ZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
dZe	 d	 	 	 	 	 	 	 	 	 dd       ZdddZd ZdddZ	y)BlocksConfigc                J    d| _         || _        i | _        i | _        d| _        y )Nr   )re   r   r   fnsfn_id)ru   r   s     rv   rw   zBlocksConfig.__init__  s%    $46-/
rx   Nc            
        |D  cg c]4  } |s"| j                   r| j                   j                  nd| j                  f6 }!} t        |t              rd}"t        |d       }nd}"|g }nt        |t              s|g}t        |t              rt        |d       }n|g }nt        |t              s|g}|	rt        |	t              s|	g}	||st        |||"       |!r||!d   d   d	v rd
}n|!d   d   dv rd}|d}n|dvrt        d| dg d       |r|j                  n|}#|#rt        |#      nd\  }$}%}&|
#t        |
t              r|
j                         dk(  r|t        |d      s<t        |d      r-t        |j                  d      r|j                  j                  }'nd}'n|j                  }'dj!                  |'D (cg c]%  }(|(t#        t$        j&                        ddhz
  vs$|(' c}(      }
n|d}
d}nd}
d}|
durat)        j*                  |
| j,                  j/                         D cg c](  }t        |j0                  t              r|j0                  * c}      }
nd}||&du}t2        j4                  j7                         })|du r|rt        d      t9        ||||fi d| j:                  d|"d|!d|d|d|d |d!|%dud"|
d#|d$|d%|	d&|d'|d(|d)|d*|d+|d,|d-|d.|d/|)d0|d1|d2|d3|d4|d5|d6| j<                  j>                  d7|}*|*| j,                  | j:                  <   | xj:                  dz  c_        |*|*j                  fS c c} w c c}(w c c}w )8a  
        Adds an event to the component's dependencies.
        Parameters:
            targets: a list of EventListenerMethod objects that define the event trigger
            fn: the function to run when the event is triggered
            inputs: the list of input components whose values will be passed to the function
            outputs: the list of output components whose values will be updated by the function
            preprocess: whether to run the preprocess methods of the input components before running the function
            postprocess: whether to run the postprocess methods of the output components after running the function
            scroll_to_output: whether to scroll to output of dependency on trigger
            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.
            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.
            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
            no_target: if True, sets "targets" to [], used for the Blocks.load() event and .then() events
            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.
            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)
            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.
            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 `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.
            is_cancel_function: whether this event cancels another running event.
            connection: The connection format, either "sse" or "stream".
            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.
        Returns: dependency information, dependency index
        NTc                    | j                   S rz   re   xs    rv   <lambda>z0BlocksConfig.set_event_trigger.<locals>.<lambda>/  s
    !%% rx   )rZ   Fc                    | j                   S rz   r  r  s    rv   r  z0BlocksConfig.set_event_trigger.<locals>.<lambda>8  s
    AEE rx   r   r_   )changekey_upalways_last)streammultiplerV  )rV  r  r  z,Invalid value for parameter `trigger_mode`: z. Please choose from: NNNrY  r   r   unnamed-r   js_fnz<Cannot create event: events with js=True cannot have inputs.re   r*  r+  r&  r'  r$  r%  r#  r,  r-  r.  r/  r0  r1  r2  r3  r4  r5  r7  r8  r   rm   r=  r@  r>  r?  rA  rB  r   rD  ) rR  re   
event_namerg   r	   sortedr   rK   r   r  r7   rh   stripr   r   r   joinrp   stringpunctuationr   append_unique_suffixr}  r   r,  r"   r   rc   r  r~  r   r   )+ru   r+  r  r   r!  r"  r  r7  r.  r/  r,  r-  	no_targetr5  r&  r'  r0  r1  r2  r3  r4  r$  r%  r8  r   r=  r@  r>  r?  rA  rB  rD  target_targetsr*  fn_to_analyzer   progress_indexevent_data_indexr   srm   block_fns+                                              rv   set_event_triggerzBlocksConfig.set_event_trigger  si   h "

  )2fll  !!
 
 fc"!NF8F"N~1 gs#W/:G_GGX.iGJ/?$J 01>''FNC,{1~!55,!Q:-)!L!DD>|nLb  dG  cH  I  *4
+8L'>P 	,>+
 z(C8X^^=MQS=S~r:.r;/GBLL*4U!||44(;;D77 $V1V5G5G1HCQT:1U(UQV " $ 5 11 #hhoo/!"++s3 KKH H
 &"2$">"--113:&N  !$
 

$
 *$
 $
 $
 *$
 0$
 *$
 +$6$
 $
 $
  (!$
" .#$
$ %$
& !4'$
( ()$
* %<+$
, &-$
. /$
0 .1$
2 3$
4 "5$
6 $7$
8  29$
: ";$
< "=$
> &?$
@ 0A$
B !4C$
D --E$
F 0G$
L  (

a
%%G
r Ws   9M>%M $M +-M%
c           	        |r| |vri S t        |d      r|j                         ni }g }|r;|j                  r/|j                  j	                         D cg c]
  \  }}|	| }}}t        j                  ||       | |j                         ||j                  t        |dd       |j                         d}|r|j                  |d<   |j                  |j                  j                  |d<   |j                  s|j                         |d<   t        |d      r|j                         |d<   n|j                         |d<   t        |d	      r|j                         |d	<   n|j                         |d	<   |j!                         |d
<   |S c c}}w )Nr   )
skip_propsr  )rf   typer   r   r  rZ   r   rm   api_infoapi_info_as_inputapi_info_as_outputexample_inputs)r   r   rZ   r   ro  r   delete_noner   r   r   r}   re   rm   r  r  r  r  )	re   rendered_idsrR  r   r   skip_none_deletionpropvalblock_configs	            rv   config_for_blockzBlocksConfig.config_for_block  s    #\1I&-e\&B  "599 ',&<&<&B&B&D""s" " 	%,>? ((*")%1Et"L##%
 )3L&(*/*;*;*?*?L'~~',~~'7L$u12494K4K4M0149NN4D01u235:5M5M5O125:^^5E12-2-A-A-CL)*;"s   
FFc                   i g g d}| j                   j                  D ]0  \  }}||d   vs| j                   j                  g dg g d|d   |<   2 g dfd|r| j                  |j                     }n| j                   } |      }||d<   |j                  dg       D ]^  }t        |t              s|d   | j                  v s&| j                  |d      }|d   |j                     d   d   j                  |       ` t        | j                  j                               }	|	D ]^  \  }
}| j                  |
||      }|s|d	   j                  |       |d   |j                     d	   j                  |j                         ` g }| j                  j                         D ]\  }||j                  |k(  s|j!                         }|j                  |       |d   |j                     d
   j                  |d          ^ ||d
<   |S )N)r   r   dependenciesr   rf   r   )layoutr   r  c                    j                  | j                         t        | t              sd| j                  iS g }| j                  D ]  } |      }|j                  |        | j                  |dS )Nrf   r  )r   re   rg   r   r   )rR  children_layoutr  r  
get_layoutr  s       rv   r  z+BlocksConfig.get_config.<locals>.get_layout  so    		*e\2eii(( O /#E*&&v./  ))AArx   r  r   rf   r   r  )rR  rU   r   r-   )r   pagesre   r   container_idrc   rg   r   r   r   listro  r  r}  r   rm   r   )ru   r   r   r   r   r   r  
root_childrR  blocks_itemsre   r  r  r  dependency_configr  r  s                  @@rv   r   zBlocksConfig.get_config  s$   
 ,, 	GD!6&>)%)__%8%8bI"$$&(vt$	 	B Z%<%<=JJJ'!x **Z4 	TJ*d+
40@DKK0OJt$45vuzz*84Z@GG
S	T
 KK
 ' 	GJC00lE:VL< ''56N5::&|4;;EIIF	G ((//# 	XB!R^^z%A$&MMO!##$56vrww'7>>?PQU?VW		X ".~rx   c                    t        | j                        }t        j                  | j                        |_        t        j                  | j                        |_        | j
                  |_        |S rz   )r{  r   copyr   r}  r~  )ru   news     rv   __copy__zBlocksConfig.__copy__  sH    4??+YYt{{+
))DHH%JJ	
rx   c           	        | j                   j                         D ]  }||j                  |k7  rt        |t        j
                        s0|j                  s=|j                  \  }}}t        |      dkD  }|| j                  dfgz  }| j                  |D cg c]
  }t        |  c}|||| |rdnd      d   }|j                         |_         yc c}w )zYAdd a load event for every component whose initial value requires a function call to set.Nr   loadhiddenrU  )r  r.  )r   r   rm   rg   r   rQ   load_event_to_attachlenr   r  r0   r   
load_event)	ru   rm   rw  load_fntriggersr   
has_targettriggerdeps	            rv   attach_load_eventszBlocksConfig.attach_load_events  s    ++- 	8I&9+@+@K+O9j&:&:;22,5,J,J)6 ]Q.
doov677 ,,BJKw('2K",n.8(f -   (+~~'7	$)	8 Ls   C
)r   Blocks)TTFrU  NNNFTFrS  NNNFrV  rT  NTNFrW  NrX  FNN)@r+  zSequence[EventListenerMethod]r  rZ  r   dComponent | BlockContext | Sequence[Component | BlockContext] | Set[Component | BlockContext] | Noner!  r  r"  r   r  r   r7  r   r.  r_  r/  z&Component | Sequence[Component] | Noner,  zstr | None | Literal[False]r-  r^  r  r   r5  r   r&  r   r'  r\  r0  r`  r1  bool | Noner2  r   r3  r   r4  z1Literal['once', 'multiple', 'always_last'] | Noner$  r]  r%  r   r8  r   r   ra  r=  r   r@  rb  r>  rc  r?  rd  rA  r   rB  r   rD  r   r   ztuple[BlockFunction, int]rz   )
re   r\  r  	list[int]rR  zBlock | Componentr   ra  r   r   )r   ra  )rm   ra  )
r   r   r   rw   r  staticmethodr  r   r  r  r   rx   rv   r{  r{    s6   2   !&>DCG04)-$(+/$((-JP=F%)(,#(/4#'!"'04(,YR&.R& R&
R&R&$ %R&& 'R&( )R&* <+R&, A-R&. ./R&0 '1R&2 3R&4 5R&6 7R&8 9R&: ";R&< )=R&> "?R&@ "&AR&B HCR&D ;ER&F #GR&H IR&J &KR&L !MR&N -OR&P !QR&R SR&T  UR&V .WR&X &YR&Z 
#[R&h 
 )-	+++ !+ &	+
 
+ +Z9v8rx   r{  launchr5  	integrater  unloadc                  x    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 d8	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9 fdZed:d       Zej                  d;d       Zed<d       Zd=dZ	ed	        Z
e	 	 	 	 	 	 	 	 d>d
       Zd Zd Zed        Zd?dZd Zd@dAdZddddBdZ	 	 	 	 	 	 dC	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDdZdEdZdFdZdGdZ	 dH	 	 	 	 	 	 	 dIdZdJdZ	 	 	 	 	 	 	 	 dKdZ	 	 dL	 	 	 	 	 	 	 	 	 	 	 	 	 dMdZ	 dH	 	 	 	 	 	 	 	 	 	 	 	 	 dNdZ	 	 	 	 	 	 	 	 	 	 dO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dPdZ	 	 	 	 	 	 dQdZd  Zd! Z dRd"Z!dHdSd#Z"d$ Z#dTdU fd%Z$d& Z% e&       	 	 	 dVd'd(	 	 	 	 	 	 	 dWd)       Z'd* Z(	 	 	 	 	 	 	 	 	 	 	 dXd+d,dddddde)jT                   ddddd-ddddddddddddddd.	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dYd/Z+	 	 	 dZ	 	 	 	 	 d[d0Z,d\d]d1Z-	 	 d^d2Z.d3 Z/d4 Z0dHd_d5Z1e2	 	 	 	 	 	 	 	 d`d6       Z3 e&       dTdad7       Z4 xZ5S )br  a  
    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_kinematics
    Guides: blocks-and-event-listeners, controlling-layout, state-in-blocks, custom-CSS-and-JS, using-blocks-like-functions
    NFc           	     
    d _         |t               }nTt        |t              rD|j	                         t
        v rt
        |j	                            }n	 t        j                  |      }t        |t              st        j                  d       t               }| _        |j                          _        |j                   _        t!        j"                         }|j%                   j                  j'                  d             |j)                          _        d _        d _        d _        d _        t5        t6               _        t5        t6               _        d _        |
 _        | _         | _!        g  _"        |xs d	 _#        tI        jJ                  |      }|xs g D ]>  }tM        |d
      5 } xjF                  d|jO                         z   z  c_#        ddd       @ |xs d	 _(        |xs d	 _)        tI        jJ                  |	      }	|	xs g D ]>  }tM        |d
      5 } xjR                  d|jO                         z   z  c_)        ddd       @ g  _*          d _+        d _,        d _-        ||nt]        j^                          _/         j^                  rEt`        jb                  sHte        jf                  t\        jh                        }|jk                          ndtl        jn                  d<   d _8        ts                _:        tw           dddi| | _=        d _>        d _?        d _@        d _A        d _B        tI        j                         du  _D        tI        j                          _E        d _F        d _G        t        tm        j                  dd	             _J        t        j                  d       _M        t                _O         j                  g _P        | _Q        t`        jb                    _R        d _S        d _T        d _U        d _V        d _W        d _X        d _Y        g  _Z        g  _[        tl        jn                  j                  dd	       _]        t                _^        dg __        d	 _`         j^                  rvt         fdt
        j                         D               } jz                   jF                  du j                  j                  |t               d}t]        j                  |        j                          y# t        $ r9}t        j                  d| dt        |              t               }Y d}~d}~ww xY w# 1 sw Y   xY w# 1 sw Y   axY w)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 Hugging Face 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. Used internally for analytics.
            title: The tab title to display when this is opened in a browser window.
            css: Custom css as a code string. This css will be included in the demo webpage.
            css_paths: Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.
            js: Custom js as a code string. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags.
            head: Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
            head_paths: Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.
            fill_height: Whether to vertically expand top-level child components to the height of the window. If True, expansion occurs when the scale value of the child components >= 1.
            fill_width: Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. Only applies if this is the outermost `Blocks` in your Gradio app.
            delete_cache: A tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.
        NzCannot load z. Caught Exception: z1Theme should be a class loaded from gradio.themeszutf-8FT(   rY  )encoding
)r  TrueHF_HUB_DISABLE_TELEMETRYrY   GRADIO_WATCH_DIRS@   GRADIO_ROOT_PATH)rY  Homec              3  t   K   | ]/  }j                   j                         |j                         k(   1 y wrz   )themeto_dict).0built_in_themeru   s     rv   	<genexpr>z"Blocks.__init__.<locals>.<genexpr>  s4      &" 

""$(>(>(@@&s   58)mode
custom_cssr  is_custom_themeversionr   )glimiterDefaultThemerg   rh   r   rS   Themefrom_hub	Exceptionwarningswarnr  _get_theme_css	theme_css_stylesheetsstylesheetsr   r   rf  r   r   
theme_hashencryptshareenable_queuemax_threadsr   r   pending_streamspending_diff_streams
show_errorfill_height
fill_widthdelete_cacheextra_startup_eventscssr   none_or_singleton_to_listopenreadr-  headrenderablescustom_mount_pathpwa
mcp_serverr   analytics_enabledr   IS_WASM	threadingThreadversion_checkstartosenvironenable_monitoringr{  default_configsuperrw   r  
is_running	local_url	share_urlwidthheightr6  api_openspace_idfavicon_pathauthr   getenvdev_moderandomgetrandbitsapp_idrp   upload_file_setr   titler8  predictinput_componentsoutput_componentsr   api_modeprogress_tracking
ssl_verifyallowed_pathsblocked_pathsrc   	root_path
proxy_urlsr  r   rr  r   r   rO   initiated_analyticsr5  )ru   r  r  r  r!  r  	css_pathsr-  r  
head_pathsr  r  r  r   r   theme_hashercss_pathcss_file	head_path	head_filetr  r   r   s   `                      rv   rw   zBlocks.__init__X  s   > = NEs#{{}/'6+!NN51E %'MMMN NE!
--/ --~~'DNN11':;&002
 *40$/$5!&$(SU!9"33I>	!R 	3Hh1 3XD8==?223 3	3 (JB	44Z@
#)r 	5Ii'2 5i		TINN$444	5 5	5 .0-1 !, ,,. 	
 !!%%$$I,C,CD	5;BJJ12.2*40000	
)T1) 	RYY':B?@((,"u#334
&...  $!%!%(:B?%-9N
!!"% &&5&<&<&>& # O
 		"hhd2#2.0D ))$/

Y ! +MML7KCPQF8"TU(NE+63 35 5s0   T 7'U#)'U0	U '.UU #U-	0U:	c                .    | j                   j                  S rz   r  r   r|   s    rv   r   zBlocks.blocks  s    "")))rx   c                &    || j                   _        y rz   r6  )ru   rV   s     rv   r   zBlocks.blocks  s    %*"rx   c                .    | j                   j                  S rz   )r  r}  r|   s    rv   r}  z
Blocks.fns  s    ""&&&rx   c                    | j                   |   }t        |t        j                  t        f      st        d| d      |S )NzBlock with id z# is not a Component or BlockContext)r   rg   r   rQ   r   	TypeError)ru   rf   comps      rv   get_componentzBlocks.get_component  s>    {{2$!5!5| DEnRD0STUUrx   c                J    t         j                  ryddlm} t	        |dd      S )NFr   )reload_threadrunning_reload)r   r  gradio.cli.commands.reloadr>  r   )ru   r>  s     rv   _is_running_in_reload_threadz#Blocks._is_running_in_reload_thread   s#     <}&6>>rx   c           	     b   t        j                  |      }|d   |j                  dd      }i hd)fdfddg}t        |      5 }t        j
                  xs |xd	<   }d
|v r |d
   j                  dg              d}d|vrt        d      t        |d   |d      D ]	  \  }	}
d|	v r	|	d   dk(  r|D ]  }|	j                  |d        |	j                  d      }|	j                  dd      }d}t        |d	   t              s%|d	   d   dv rt        |      dk7  rt        d      d}|	j                  d       |	j                  dd       |	d   D cg c]  }|   	 c}|	d<   |	d   D cg c]  }|   	 c}|	d<   |	j                  dd       |	j                  dd       |	j                  dd       |	j                  dd       |	j                  dd       |	j                  d d       d|	d!<   d|	d"<   |r;t        dd#      g}|	j                  d$      |	d$<   |	j                  d%      |	d%<   d|	d&<   nPt        j                  ||      D cg c]0  }t        |j                  r|j                  nd|j                         2 }} |j"                  j$                  d*||
d'|	d	   }	||	} |rEt'               r;|d	   g|_        |j*                  |_        |j.                  |_        d(|_        d|_        ddd       _        |S c c}w c c}w c c}w # 1 sw Y   !xY w)+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.
        proxy_url: an external url to use as a root URL when serving files for components in the Blocks.
        r   r  rT  rf   c                   D ]  }|d   | k(  s n t        d|        t        |d   d         }|d   j                  d      	 d|d   d<   |d   j                  dd       }|j	                  |d         } |d	i |}|||_        |d   d   }||_        
j                  |       |d   j                  dd       x}	 ||_        |S )
Nrf   zCannot find block with id r   r   r]   /rV   r   r   )	r   rL   rc   r   r   rV   r]   r   r   )rf   r  r   postprocessed_valuer   rR  block_proxy_urlr   components_configr]   r+  s           rv   get_block_instancez.Blocks.from_config.<locals>.get_block_instance!  s    1 D%+D !#=bT!BCC+L,A&,IJC
 G$((5=8A{!_W%k2".w"7";";GT"J"11,w2GH+*+E".1*73K@O-EONN?++G488MM %0!Lrx   c                    | D ]Z  }|d   } |      }||<   |j                  d      }|)t        |t              st        d| d      |5   |       d d d        \ y # 1 sw Y   gxY w)Nrf   r   zInvalid config, Block with id z( has children but is not a BlockContext.)rc   rg   r   r   )children_listchild_configrf   rR  r   rH  iterate_over_childrenoriginal_mappings        rv   rL  z1Blocks.from_config.<locals>.iterate_over_children?  s     - 8!$'*2.', $'++J7'%e\:(<RD@hi   8-h78 888 8s   	A""A+	rN  )r  r   r  r   Nr  zEThis config is missing the 'dependencies' field and cannot be loaded.Fstrictr  
fake_eventr+  r_   )thensuccesszcThis logic assumes that .then() events are not combined with other events in a single gr.on() eventTrM  documentationr   r!  status_trackerzerogpurm   rQ  everyr"  r  rQ  r2  r3  r  )r+  r  	Interface)rf   r\  r   rU   r   )r  deepcopyrc   r  r!   r   r   zipr   rg   r\  r  r0   get_event_targetshas_trigger__self__r  r  r  r#   r"  r   r#  r!  r$  r   r%  r+  )r   r   r}  r]   r  derived_fieldsr   r   first_dependency
dependencyr  fieldr  r  is_then_eventior+  r4  rG  rH  rL  rM  r+  s      `               @@@@@rv   from_configzBlocks.from_config  s     v&"<0

7I.-/[
	<	8  "%  Y	'F/6/A/A/KVKQ*6!%fX&6&:&::r&JK# V+ [  #&f^&<c%"P C2
B 
*z)/D/T+ 0ENN5$/0
 &>>)4$..D9 %
 "(1+s3A K 9 8})( B  %)M|,51;H1E(,-$Q'(
8$ 2<I1F),-$Q')
9% /6y$/tT*}d3{D1w-+0
<(,1
=) 24@AG2<..2QJ/<FNN1=J89 /3J{+ "(!9!9,h"
 	 ,*+--AJJTLLG  IZ66HH #.8
 $+'1$GC2L  $6$8"%a&*:*A*A'+;+C+C("-"&sY	't '[()&IY	' Y	's?   DL%%L1L%>L
CL%5L &L%9AL%L%%L.c                "    | j                         S rz   )rK  r|   s    rv   rI  zBlocks.__str__  s    }}rx   c                
   t        | j                  j                         D cg c]  }|j                  s| c}      }d| d}|ddt        |      z   z  }| j                  j	                         D ]  \  }}|j                  s|d| z  }|dz  }|j
                  D ]#  }| j                  |j                     }|d| z  }% |dz  }|j                  D ]#  }| j                  |j                     }|d| z  }%  |S c c}w )	NzGradio Blocks instance: z backend functionsr  r  z

fn_index=z	
 inputs:z
 |-z

 outputs:)	r  r}  r   r  ro  r   r   re   r!  )ru   dnum_backend_fnsreprr_  rR  s         rv   rK  zBlocks.__repr__  s   $((//*;DQqttqDE)/)::LM"S3t9_%&&!XX^^- 
	,MAz}}+aS))$'.. ,E KK		2EeE7O+D, %'// ,E KK		2EeE7O+D,
	,  Es
   D D c                V    t        d | j                  j                         D              S )z>Return whether the app expects user to authenticate via OAuth.c              3  P   K   | ]  }t        |t        j                           y wrz   )rg   r   LoginButtonr  rR  s     rv   r  z'Blocks.expects_oauth.<locals>.<genexpr>  s"      
:?Juj445
s   $&)rr  r   r   r|   s    rv   expects_oauthzBlocks.expects_oauth  s+      
CG;;CUCUCW
 
 	
rx   c                x    | j                   j                  t        dd      g|dddddddddddddddddd	       y)
aI  This listener is triggered when the user closes or refreshes the tab, ending the user session.
        It is useful for cleaning up resources when the app is closed.
        Parameters:
            fn: Callable function to run to clear resources. The function should not take any arguments and the output is not used.
        Example:
            import gradio as gr
            with gr.Blocks() as demo:
                gr.Markdown("# When you close the tab, hello will be printed to the console")
                demo.unload(lambda: print("hello"))
            demo.launch()
        Nr  Fr  TrS  rV  rT  )r+  r  r   r!  r"  r  r.  r,  r-  r  r&  r'  r0  r1  r2  r3  r4  r$  r%  r8  )r  r  r0   )ru   r  s     rv   r  zBlocks.unload  sc     	--(x89" $$)') 	. 	
rx   c                .   t               }|t        j                  | j                  |j                  v rt        d| j                   d      t        |j                        j                  | j                        }|D ]4  }t        | j                  |   t        j                        r+t        d       | j                  j                         D ]!  }t        j                  j                  |_        # |j                  j                  | j                         t        |j                   j#                         d      dz   }|j                   j                         D cg c](  }t        |j$                  t&              r|j$                  * }}| j                   j                         D ]d  }t        j                  j                  |_        |xj                  |z  c_        |j(                  D ]4  }	|	d   | j                  k(  st        j                  j                  |	d   f}	6 |j$                  }
t        |
t&              r"t+        j,                  |
|      }|
|k7  r||_        |j.                  D cg c]  }||z   	 c}|_        |j0                  |xj0                  |z  c_        |j.                  rD|j.                  D cg c]  }|j                   |   j3                         ! }}t5        |      |_        ||j                   |j                  <   g t        |j                   j#                         d      dz   |_        t        j                  j8                  j;                  | j8                         t        j                  j<                  j                  | j<                         t        j                  j>                  j;                  | j>                         tA               }|%|jB                  j;                  | jB                         | S c c}w c c}w c c}w )Nr   r   z<At least one block in this Blocks has already been rendered.)rT  r_   r   )"r#   r!   r   re   r   r2   rp   intersectionrg   r   Stater   r   r   rf  maxr}  keysr,  rh   r+  r   r  r0  r2  r   rM   r~  r   extendr+  r  r$   r   )ru   r   overlapping_idsrf   rR  dependency_offsetr  existing_api_namesr_  r  r,  	api_name_crb  updated_cancelsr   s                   rv   rY   zBlocks.render  sm   )+#(:(:(Fxx<...)'z1bc  ","5"56CCDKKPO% !$++b/:3C3CD-V  ++- =$//<<
=&&t{{3 #L$4$4$9$9$;R H1 L (++224"cllC0 " "
 #hhoo/ >
")"4"4"A"A
"33 )00 EFayDHH,")"4"4"8"8&)!DE &..h, % : : *!I  9,.7
+EOEWEW%Xa*;&;%X
"++7,,0AA, %%BLBTBT'=>((+668'O ' *B/)RJ&3=  07>8 "%\%5%5%:%:%<b!IA!ML--44T5H5HI))00A33::4;T;TU+-%##**4==9S"* &Y's   -P.P=$Pr   c                2   | j                   |   }| j                   |   }t        j                  |j                        ryt        j                  |j                        ryt        d |j                  D              ryt        d |j                  D               S )zVChecks if a particular Blocks function is callable (i.e. not stateful or a generator).Fc              3  4   K   | ]  }|j                     y wrz   r   rm  s     rv   r  z%Blocks.is_callable.<locals>.<genexpr>3  s     =%u~~=   c              3  4   K   | ]  }|j                     y wrz   r  rm  s     rv   r  z%Blocks.is_callable.<locals>.<genexpr>5  s     F%u~~Fr  )r}  r   r:  r  r9  rr  r   r!  )ru   fn_indexr  r_  s       rv   is_callablezBlocks.is_callable*  sy    88H%XXh'
%%hkk2&&x{{3=:+<+<==F:3E3EFFFFrx   )r  r,  c               D   ?t        fd| j                  j                         D        d      }|t        d       |}| j	                  |      st        d      t        |      }| j                  ||      }| j                  |   }|j                  r|D cg c]  }|g }}t        j                  | j                  ||di d      }|d   }|j                  r|D 	cg c]  }	|	d   	 }}	| j                  ||      }t        j                  |      }
|
S c c}w c c}	w )	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  H   K   | ]  \  }}|j                   k(  s|  y wrz   )r,  )r  rb  rg  r,  s      rv   r  z"Blocks.__call__.<locals>.<genexpr>D  s      Jtq!1::3IJs   ""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.T)r  r   requeststateexplicit_callr   r   )nextr}  ro  r3   r  r   r  serialize_datar&  r   synchronize_asyncprocess_apideserialize_datar   rq  )ru   r  r,  r   inferred_fn_indexprocessed_inputsr  inpr!  outprocessed_outputss     `        rv   __call__zBlocks.__call__7  sA     $Jtxx~~/J! !();H:F  )H  * r  f..x@XXh881AB#BB00#
 &/88)01#s1v1G1''':!33G<  %  C 2s   
D!Dc	                D  K   t        |t              r| j                  |   }|j                  st	        d      d}	t        |t
              r|d   n|}
t        j                         }t        j                  |j                  | |||
|      }||j                  r"t        t        |j                  |d            g}|j                  r|j                  j                  n|j                  }t        |||
|      \  }}}|||   nd}| |t        ||j                         \  }}|||<   t#        j$                  |      r ||  d{   }n8t'        j(                  j*                  |g|d| j,                  i d{   }nd}t#        j.                  |      st#        j0                  |      rn	 |t3        t4        t6           |      }t#        j8                  |      r t        j:                  || j,                        }t        j<                  |       d{   }d}	t        j                         |z
  }|||	|d
S 7 7 7 (# t>        $ rW tA        |jB                        }|d	k(  rtD        jF                  jH                  ntD        jF                  jH                  f|z  }d}Y w xY ww)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 has no backend method.Fr   )r  r   event_idin_event_listenerr  r  NrN  r  Tr_   )
predictiondurationis_generatingiterator)%rg   r\  r}  r  
IndexErrorr  timer   get_function_with_localsr*  r   rY  r   r   r7   r5   
track_tqdmr   iscoroutinefunctionanyio	to_threadrun_syncr  r9  r:  r   r   r   isgeneratorSyncToAsyncIteratorasync_iterationStopAsyncIterationr  r!  r   rh  FINISHED_ITERATING)ru   r  processed_inputr  requestsr  
event_datar  r  r  r  r  r  r  r  r   progress_trackerr  	n_outputsr  s                       rv   call_functionzBlocks.call_functioni  s    * h$xx)H{{>??!+Hd!;(1+		++{{/
 &&X__oeLM#
 +3*=*=##&&8;;  2>2.O^Q 4B3M/SW   +0J'5b:J:U:U'V$ "2B/**2.#%#77
#(??#;#;$($26,,$ 
 J&&r*g.H.H.L ##M#$6
CH&&x0$884<<PH#(#8#8#BB
 $ 99;& % * 	
 	
7 8 C%   0 01	 !A~ ((;;$..AACiO 
   s\   EJ H75J 9H9:1J ,A&H= H;H= J 9J ;H= =AJJ JJ c                z   | j                   |   }g }d }t        |j                        D ]  \  }}t        |t        j
                        st        |j                   d      |j                         }t        j                  |      rt        j                  ||   |d       }	n||   }	|j                  |	        |S )Nc                6    t        |       j                         S )N)r   )r*   r   r  s    rv   format_filez*Blocks.serialize_data.<locals>.format_file  s    #..00rx   ' Component not a valid input component.c                Z    t        j                  |       xs t        j                  |       S rz   )r   is_filepathr   r  s    rv   r  z'Blocks.serialize_data.<locals>.<lambda>  s'    l66q9 8#44Q7 rx   )r}  	enumerater   rg   r   rQ   r4   r   r  r   value_is_filetraverser   )
ru   r  r   r_  r  r  rb  rR  r  serialized_inputs
             rv   r  zBlocks.serialize_data  s    XXh'
	1 "*"3"34 	5HAueZ%9%9:+''NO  ~~'H))(3#/#8#81I8$  $*!9 ""#34	5" rx   c                :   | j                   |   }g }t        |j                        D ]q  \  }}t        |t        j
                        st        |j                   d      t        j                  ||   d t        j                        }|j                  |       s |S )N( Component not a valid output component.c                    | d   S )Nr   r   r  s    rv   r  z)Blocks.deserialize_data.<locals>.<lambda>  s
    ai rx   )r}  r  r!  rg   r   rQ   r4   r   r   r  is_file_objr   )ru   r  r!  r_  rt  rc  rR  deserializeds           rv   r  zBlocks.deserialize_data  s    XXh'
!*"4"45 		-HAueZ%9%9:+''OP  (00
/1I1IL |,		- rx   c                   |j                   }t        |      t        |      k  r|j                  r|j                  dk7  rd|j                   dnd}g }g }|D ]  }|j                  t	        |              |D ]4  }t        |t              rd| dn
t	        |      }	|j                  |	       6 dj                  |      }
dj                  |      }t        d| dt        |       d	t        |       d
|
 d| d      y )N<lambda> ()rY  ", z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   r   rh   rg   r  r   )ru   r  r   
dep_inputsr   wanted_argsreceived_argsrR  r  vwantedreceiveds               rv   validate_inputszBlocks.validate_inputs  s&   __

 v;Z( ==X]]j%@ X]]O1%  KM# /""3u:./ (",S#"6auAJCH$$Q'( YY{+Fyy/H $TF*WX[\fXgWhhopstzp{o| } X Zq ' )rx   c                  K   |xs t        |       }| j                  ||       g }t        |j                        D ]  \  }}t	        |t
        j                        st        |j                   d      |j                  r|j                  ||j                            d|j                  |v r||j                     }t        j                  ||   ||        d {   }t        |dd       r>|<t        t         t"        t$        f   |j&                        }	|	j)                  |ddi      }t	        |t"        t$        f      r|j+                         }
n|}
|j                  |vr|||j                  <   |j-                  |j                  |
       |j.                  r"|j                  |j/                  |             |j                  |
        |S 7 w)Nr  )check_in_upload_folder
data_modelvalidate_metaT)context)rA   r  r  r   rg   r   rQ   r4   r   r   r   re   r   async_move_files_to_cacher   r   r   r+   r,   r  model_validater   _update_value_in_configr"  )ru   r  r   r  r  r  rb  rR  inputs_cachedr  inputs_serializeds              rv   preprocess_datazBlocks.preprocess_data  s     +d+Xv.!(//2  	>HAueZ%9%9:+''NO  ~~&&uUYY'7899%!%)),E&6&P&P1I/<+<' !
 5,5-:S!%k?:;U=M=M"J %/$=$=%/F %> %M mk?-KL(5(@(@(B%(5%99E)',E%))$--eii9JK&&#**5+;+;M+JK#**+<=A 	>B /!s   CGGC6Gc                   |j                   }t        |t        t        f      s|g}t	        |      t	        |      k7  rK|j
                  r|j
                  dk7  rd|j
                   dnd}g }g }|D ]*  }|j                  t        |j                                      , |D ]4  }t        |t              rd| dn
t        |      }	|j                  |	       6 dj                  |      }
dj                  |      }t	        |      t	        |      k  r-t        d| dt	        |       d	t	        |       d
|
 d| d      t	        |      dk(  r|d   y t        j                  d| dt	        |       d	t	        |       d|
 d| d       y y )Nr  r  r  rY  r  r  zA  functionz- didn't return enough output values (needed: z, returned: z#).
    Output components:
        [z']
    Output values returned:
        [r  r_   r   z
A functionz* returned too many output values (needed: z:). Ignoring extra values.
    Output components:
        [)r!  rg   r  tupler  r   r   rh   r   r  r   r  r  )ru   r  rt  dep_outputsr   r  r  rR  predr  r  r  s               rv   validate_outputszBlocks.validate_outputsB  s   &&+e}5&-K{s;// ==X]]j%@ X]]O1%  KM$ A""3u'<'<'>#?@A# (#-dC#8avQKc$i$$Q'( YY{+Fyy/H;#k"22 #D6)VWZ[fWgVhhtux  zE  vF  uG G

 

1	  {#q([^-C "4&(RSVWbScRddpqt  vA  rB  qC C

 

1	? 0rx   c                  K   |xs t        |       }t        |t              rF|t               k(  r9t	        |j
                        dkD  r!t               gt	        |j
                        z  }t        |t              r<t	        |      dkD  r.t        |j
                  D cg c]  }|j                   c}|      }t	        |j
                        dk(  r|j                  s|g}| j                  ||       g }t        |j
                        D ]  \  }}	 ||   t        j                  j                  u r|j                  d        9	 |j&                  r<t)        j*                  ||         s||   ||j                  <   |j                  d        ||   }t)        j*                  |      rt)        j,                  |d      }t        |t.              r|j0                  j3                         }d|d<   t)        j*                  |      r||j                     j0                  j3                         }	|	j5                  |       |	j7                  dd        |	j7                  d       d	|	d
<    |j8                  di |	||j                  <   |j;                  |j                         t=        ||j                     ||j>                        }d|v r|jA                  |j                  |jC                  d             n|j>                  rt        |t        jD                        stG        |j8                   d      |j                  |v r||j                     }|j?                  |      }t        |tH        tJ        f      r|jM                         }
n|}
tO        jP                  |
|d       d {   }
|j                  |vr|||j                  <   |jA                  |j                  |
       tO        jP                  ||d       d {   }|j                  |        |S c c}w # t        t         f$ r}t#        d|j$                         |d }~ww xY w7 7 Qw)Nr_   r   zXNumber of output components does not match number of values returned from from function T)
skip_valuerf  rg  rV   FrY   )rR  rj  r  r  r  r   ))rA   rg   r   r6   r  r!  ry  re   r&  r  r  r   rh  r  r   r  r   r   r   r   r   is_prop_updater  rU   r   r  rf  r   r   _update_configrl  r  r  rc   rQ   r4   r+   r,   r   r   r  )ru   r  rt  r  rR  outputrb  errprediction_valuer   prediction_value_serializedoutputs_cacheds               rv   postprocess_datazBlocks.postprocess_datao  s     +d+{D)tv%H$$%)  6(S)9)9%::Kk4(S-=-A8(0(8(89u9;K x A%hnnK 	h4!("2"23 K	.HAuq>Z%9%9%L%LLMM$' M ~~++KN;'21~E%))$d##.q> ''$ (-'8'8(T($ .6'7'H'H'M'M'O$3;$Z0''(89"599->>CCEFMM"23JJw-JJz*',F8$'6u'@'@E%))$((3'>#EII.$4$,$8$8($
 "2255!II'7';';G'D ))%eZ-A-AB3$//WX  yyE) %eii 0','8'89I'J$!"2[/4RS6F6Q6Q6S36F3.HH7!(,  0 yy-+0eii(11		#> (8'Q'Q$ $( "
 n-WK	.Z q :  )  ==E]]OM j"sW   BQP,AQ0P<IQQAQ4Q5QQ#P<<QQQc           
     (  K   |||S || j                   |   vri | j                   |   |<   | j                   |   |   }t        |j                        D ]3  \  }}	|	j                  }
t	        |	t
        j                        s.|	j                  s;t        j                  ||         rT|r||
   j                          |
|v}|	j                  ||   | d| d|
 d|       d {   \  }}|rAd }|j                  d      x}rt        |      j                  dd  }t        |      ||
<   ||
    ||
   j!                  |       d {    t#        j$                  ||	d       d {   }|t#        j&                  ||d       }|||<   6 |S 7 7 I7 +w)NrD  z/playlist.m3u8	orig_namer_   )desired_output_formatTr  )r  r  r!  re   rg   r   StreamingOutput	streamingr   r  
end_streamstream_outputrc   r
   suffixr<   add_segmentr   r  add_root_url)ru   r  r   session_hashrunr*  final
stream_runrb  rR  	output_idfirst_chunkbinary_dataoutput_datar  r  s                   rv   handle_streaming_outputszBlocks.handle_streaming_outputs  s     3;Kd**<8868D  .s3-1-A-A,-OPS-T
!("2"23 "	&HAu		I5*"<"<=OO,,T!W5y)446'z9161D1DG#nAcU!I;nE2 ,([
 ,0)$/OOK$@@y@04Y0F0Fqr0J-,7.C-Jy) y) +77DDD$4$N$N $% 
 ("2"?"?#Y#K &QE"	&H 5, EsI   A>FFF';F"F#A!FFF$F%(FFFc                   |||S || j                   |   v}|rd gt        |      z  | j                   |   |<   | j                   |   |   }t        t        |j                              D ]D  }	|r	||	   ||	<   |r	||	   ||	<   ||	   }
||	   ||	<   |r)t	        j
                  |
||	         ||	<   F |r| j                   |   |= |S rz   )r  r  ranger!  r   diff)ru   r  r   r  r  r  simple_format	first_run
last_diffsrb  
prev_chunks              rv   handle_streaming_diffszBlocks.handle_streaming_diffs  s     3;Kt88FF	<@6CI;MD%%l3C8..|<SA
s8++,- 	>A$Q-Q $Q
1']
 $Q
1$#jjT!W=DG	> )),7<rx   Tc           
        K   t        |t              r| j                  |   }|j                  }| j	                  ||      \  }}g }t
        j                  j                  |        |r|j                  }|D cg c]  }t        |       }}|d    t        j                  |j                        st        j                  |j                        rt        d      t         fd|D              st        d| d       |kD  rt        d  d| d      t!        |d	d
iD cg c]'  }| j#                  |t%        |      ||       d{   ) }}| j'                  |t%        t!        |d	d
i      d||||	|       d{   }|d   }t!        |d	d
iD cg c]&  }| j)                  |t%        |      |       d{   ( }}|t+        j,                  ||d      }t%        t!        |d	d
i      }d\  }}n|}|rg }n| j#                  ||||       d{   }|du}| j'                  |||||||	|       d{   }| j)                  ||d   |       d{   }|r;t!        ||d
      D cg c]"  \  }}|t/        j0                  ||         k7  r|$ }}}|t+        j,                  ||d      }|d   |d   }}|s|rP|rt3        |      n
t3        |      }| j5                  ||||||        d{   }| j7                  ||||| |
      }|xj8                  |d   z  c_        |xj:                  dz  c_        ||||d   |j8                  |j:                  z  d|d}|j<                  re|rc|j>                  jA                  |j<                        |d<   |j<                  jB                  |d   d<   |t+        j,                  |d   |d      |d<   |S c c}w 7 c c}w 7 b7 *c c}w 7 7 7 c c}}w 7 w)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
            in_event_listener: whether this API call is being made in response to an event listener
            explicit_call: whether this call is being made directly by calling the Blocks function, instead of through an event listener or API route
            root_path: if provided, the root path of the server. All file URLs will be prefixed with this path.

        Returns a dictionary with the following keys:
            - "data": the output data from the function
            - "is_generating": whether the function is generating output
            - "iterator": the iterator for the function
            - "duration": the duration of the function call
            - "average_duration": the average duration of the function call
            - "render_config": the render config for the function
        r   z1Gradio does not support generators in batch mode.c              3  (   K   | ]	  }|k(    y wrz   r   )r  r  
batch_sizes     rv   r  z%Blocks.process_api.<locals>.<genexpr>g  s     <1qJ<s   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  rO  FNr  )NNrN  r  r  )r  r  r*  r  )r  r  r  r  r  r_   )r   r  r  r  average_durationrender_configchanged_state_idsr  rQ  )"rg   r\  r}  r&  get_state_ids_to_trackr"   r   rp   r'  r  r   r:  r  r9  r   rn  rY  r  r  r  r  r   r  r   	deep_hashrf   r  r  r(  r)  r   blocks_configr   re   )!ru   r  r   r  r  r  r  r  r  r  r  r  r*  r&  state_ids_to_trackhashed_valuesr  r'  r  batch_sizesrb  resultpredsrc  r   r  old_iteratorwas_generating
hash_valuestate_idr  r  r  s!                                   @rv   r  zBlocks.process_api1  s    N h$xx)H,0,G,GRW,X)M%%44N/563s86K6$QJ))(++6':U:U; !!TUU<<< ghsgttuv  N* ":,.^_m^nnop 
 f3U3 **8T!We]SSSF   --S&//0!	 	F <(E e2E2 ++Hd1guEEED  $'44T9dKT0%01D&0#M8#L#33fe]   *5N--!	 	F ..x9MuUUD 14%'9%1%,
H "U__U8_%EE	 %! % $'44T9dK&,_&=vj?Q8M*8b&bl!::!-'++ ;   22!-++"/ 3  	&"44q * z* ( 6 69L9L L!!2
 5&+&9&9&D&D##'F?# 4<3F3F3J3JF?#K0$*:*G*G?+Y+' [ 7 T	 F	 V%s   A5O;8O
BO;!%OO
O/O;<O=O;$O$7O!
8O$>AO;O)#O;6O,7O;O/O;,'O2AO;0O81C%O;OO;!O$$O;,O;/O;2O;c                f   |g g fS g }g }|j                   D ]  j                  st        fd|j                  j                  j                         D              sG|j                     }|j                  j                         |j                  t        j                  |              ||fS )Nc              3  R   K   | ]  }j                   d f|j                  v    yw)r  N)re   r+  )r  r  rR  s     rv   r  z0Blocks.get_state_ids_to_track.<locals>.<genexpr>  s+      & H%3&s   $')
r!  r   rr  r  r}  r   re   r   r   r
  )ru   r  r  r  r  rV   rR  s         @rv   r	  zBlocks.get_state_ids_to_track  s     =r6M%% 	=E~~# &--1188:& # eii("))%))4$$U__U%;<	= "=00rx   c                h    | j                   dk(  rd | _        y t        | j                         | _        y )Nr  )total_tokens)r  r   r  r|   s    rv   create_limiterzBlocks.create_limiter  s5     2%  	 !d.>.>? 	rx   c                
    ddiS )Nr  columnr   r|   s    rv   r   zBlocks.get_config  s    !!rx   c                x   i dt         dt        d| j                  d| j                  d| j                  d| j
                  dg d| j                  d	d
dt        t        t        d   z  d z  | j                        d| j                  d| j                  xs dd| j                  dddt        | dd
      d| j                  dt!        j"                         t        | dd       | j$                  | j&                  j(                  d| j&                  j+                  d      | j&                  j+                  d      | j&                  j+                  d      | j&                  j+                  d      d| j,                  | j.                  | j0                  | j2                  | j4                  i | j6                  t        | dd       t        | j8                  dd       nd d}|j;                  | j<                  j?                                t!        j@                  || jB                  jE                               |d	<   |S )Nr  
api_prefixr  r  r  r  r   r  connect_heartbeatFr-  Tr  r!  Gradior  r  r  r8  is_colabmax_file_sizesse_v3body_background_fillbody_text_colorbody_background_fill_darkbody_text_color_dark)r#  r$  r%  r&  i18n_instancetranslations_dict)r!  r  r  protocolbody_cssr  r  r  r  r  r   r  i18n_translations)#r>   r;   r  r  r  r  r  r   rh   r   r-  r  r!  r  r   r8  r   colab_checkr  r  r   _get_computed_valuer  r  r  r  r  r  r'  rf  r  r   r  r   r   )ru   r   s     rv   get_config_filezBlocks.get_config_file  sT   .$
w.$
*.$
 DII.$
 dkk	.$

 .$
  !7!7.$
 ".$
 488.$
  .$
 $sWT]*T1477;.$
 DII.$
 TZZ+8.$
 .$
 D.$
 '$e<.$
  !.$
" ))+#.$
$ %T?DA++ZZ__ (,

(F(F*) $(::#A#ABS#T-1ZZ-K-K/. )-

(F(F*)  ++////88ZZ// 4$7C **,?FY.$
^ 	d))4467&+&=&=DKK&&('
"# rx   c           
     V   | j                   j                         D cg c]*  }|j                  s|j                  du s|j                  , }}t	        |      }|s|dkD  rt        d       t        d       t        |      D ]g  \  }}|s$t        d|dz    d| d|j                   d	d
       t        |dd       !	 t        |d      |_
        |st        d       Z|r]t        d       i |s|dkD  rt        d       y y y c c}w # t        $ r}|st        d|d       Y d }~d }~ww xY w)NTr   z,********************************************zB* Trying to transpile functions from Python -> JS for performance
z* (r_   rD  z) z: rY  )endr<  )validateu   ✅u   ❌z

z-********************************************
)r}  r   r  r-  r  printr  r   r   r   r<  r  )ru   quietr  fns_to_transpilenum_to_transpilerp  r   s          rv   transpile_to_jszBlocks.transpile_to_js!	  s,    HHOO-
255D=BEE
 
 /0)A-@AWX"#34 	IE2EAI;a(8'9BKK=KQSTr2D9A4/8d/KB, e e	 )A-BC .u)
 ! 4 eQF34s'   D D D ;D	D(D##D(c                f    t               }|| t        _        || _        t	        |        d| _        | S r   )r$   r!   r   rl   r%   exitedr
  s     rv   r  zBlocks.__enter__9	  s3    +-!!%G$4 rx   c                   |t        d        d t        _        y t        |           t        | j
                         | j                  j                          | j
                  d t        _        n/| j
                  j                  j                  | j                         | j                         | _        t        j                  |       | _        t        d | j                   j#                         D              | _        d| _        d| _        y )Nc              3  4   K   | ]  }|j                     y wrz   )r#  )r  r  s     rv   r  z"Blocks.__exit__.<locals>.<genexpr>Q	  s      %
)1H$$%
r  rY  T)r%   r!   r   r  r  rl   r  r  r   rv  r.  r   r?   
create_appapprr  r}  r   r&  r   r8  )ru   r  r  r   s      rv   r  zBlocks.__exit__B	  s    t$!%G%'4;;'..0;;!%GKK  ''6**,>>$'!$ %
59XX__5F%
 "
 	rx   c                X    i | j                   _        i | j                   _        g | _        | S )z'Resets the layout of the Blocks object.)r  r   r}  r   r|   s    rv   clearzBlocks.clearW	  s*    %'""$rx   not_set)default_concurrency_limitc                   ||| _         t        j                         r|dn|}t        j                  |dk(  | j
                  |dk7  r|nd|| |      | _        t        j                  |       | _	        | S )a  
        By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed.
        Parameters:
            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.
            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.
            default_concurrency_limit: The default value of `concurrency_limit` to use for event listeners that don't specify a value. Can be set by environment variable GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.
        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()
        r_   auto)live_updatesconcurrency_countupdate_intervalsmax_sizer   r@  )
r  r   is_zero_gpu_spacer   Queuer  _queuer?   r;  r<  )ru   status_update_rater  rF  r@  s        rv   r5  zBlocks.queue^	  sx    6 $DM""$$,q(Hnn+v5"..3E3O/UV&?
 >>$'rx   c                    | j                   j                         D ]]  }|j                  D ]&  }| j                   |   j                  rt	        d       |j
                  sE|j                  du sTt	        d       y )Na!  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()Fz4In order to use batching, the queue must be enabled.)r}  r   r0  r5  r   r&  )ru   r  rb  s      rv   validate_queue_settingszBlocks.validate_queue_settings	  st    88??$ 	YC[[ xx{(($+  yySYY%/ !WXX	Yrx   i  z100%ra   )r  r  r  ssl_keyfilessl_certfilessl_keyfile_passwordr'  r3  r8  r(  r)  r*  
app_kwargsro   share_server_addressshare_server_protocolshare_server_tls_certificateauth_dependencyr!  r  strict_corsnode_server_name	node_portssr_moder  r  	_frontendi18nc               ~   ddl m}( | j                  ry| j                  s| j	                          ||t        d      |r:t        |      s/t        |d   t              st        |d   t              s	|g| _
        n|| _
        | j                  rwt        | j                        sbt        d | j                  D              rt        j                  d       t        d | j                  D              rt        j                  d	       || _        |	| _        || _        || _        || _        || _        || _        |&t*        j,                  j/                  d
d      | _        n|| _        || _        |r|| _        nht*        j,                  j/                  dd      })t7        |)      dkD  r3|)j9                  d      D *cg c]  }*|*j;                          c}*| _        ng | _        |r|| _        nht*        j,                  j/                  dd      }+t7        |+      dkD  r3|+j9                  d      D *cg c]  }*|*j;                          c}*| _        ng | _        t        | j4                  t              st        d      t        | j<                  t              st        d      | j?                          tA        jB                  |      | _"        | jF                  rA| jH                  jK                         D ]$  },|,jL                  d|,jN                   d|,_&        & |$tA        jP                         dun|$| _)        || _*        || jV                  _,        | j[                  |       t\        j^                  rdn*|#|#n&t+        j`                  dd      jc                         dk(  | _2        | jd                  rkt*        j,                  j/                  dt\        j^                  rdn	tg                     | _4        tk        |!|"| jh                        \  | _6        | _7        | _8        ndx| _6        x| _8        | _7         |(jr                  | ||| | jd                        x| _:        | _;        tx        dz   }-|%1t*        j,                  j/                  dd      jc                         dk(  }%|%r^	 ddl=}.	 |.j~                  j                  |       | _A        | j                  j                  | jt                  |-| j0                         d| _C        | j                         | _G        | j                  rBt        | j                  t              st        d| j                         |sjt        d        n]t\        j^                  r(d!}
d"}d}0d}1t]        j                  | jv                         n,dd#lLmM}2 |2j                  | jv                  |
||||$      \  }
}}0}1|
| _O        |0| _I        | j                  j                  d%       tx         d%| _Q        || _R        |1| _S        d| _H        tA        j                         | _U        tA        j                         | _V        || _W        |xs |d&nd'| _X        || _Y        d| _Z        | j                  j                  d'      s| j                  rd'nd&| _\        t\        j^                  sX| j                  sL|sJ| jd                  rd(nd)}3t        |3j                  | j                  | j                  | j                               | jV                  j                  | jt                         t\        j^                  sWt        j.                  | j                   d*|d+      }4|4j                  sYt        d,|4j                   d-|4j                   d.      | j                          t        j                  | j                                |f| j                  s| j                  r|st        d/       d| _g        n@d| _g        t+        j`                  d0      }5|5"|5jc                         dk(  rd| _g        n|| _g        |r/t        d1| j                   d2| jv                  j                          |d3v | _i        |'| _j        |&rFt\        j^                  s6t        j                  | j                        s| j                  st        d4      | j                  r2|s0|rt        d5       nt        d6       | j                  st        d7       | j                  rT| j                  rt        j                  d8       d| _g        t\        j^                  rt        j                  d9       d| _g        | j                  r	 | j                  xt        j                  | j                  | j                  | j                  | j                  | j                  :      }6t        |6      }7t        | j                  f|7d;d z         | _n        t        d<| j                          |st        d=       n$|st\        j^                  st        dF       d| _n        | j                  rHt        dG| j                  xs | j                  j                  d%       d%|-j                  d%       dH       |rUt\        j^                  sE| j                  r| j                  r| j                  n| j                  }8t        j                  |8       |tA        j                          }|r	 ddIlm}9m}:m}; | j                  r| j                  rt        j                  | j                        s7t        j                  dJ       t        j                  | j                        s7 |9dK| j                   dL| j"                   dM| j                    dN      }<n| j                  rdOdPj                  t        j                  | j                        t        j                  d%      t        j                  | j"                        t        j                  | j                         t        j                  d      Q      z   }= |:|=      }<n0 |9dK| j                   dL| j"                   dM| j                    dN      }<|<| _         |;|<       t        | dRd      rN|rdSndT| j                  | j                  | j                  du| j                  dU}>t        j                  | |>       t        t        t        dVt        j                  j                               }?|sGt#        t+        j`                  dWdX            d;k(  rt\        j^                  r|s#|?s!t\        j^                  s| j%                          t'        | jt                  | j                  | j                  f      S c c}*w c c}*w # t|        $ r}/t}        d      |/d}/~/ww xY w# t        $ r"}/d| _C        |st        d|/        Y d}/~/d}/~/ww xY w# t        $ r}/| j                  rt        j                  d>       d| _n        d| _g        t        |/t              rt        d?t         d@       nPt        t              j                         rt        dA       n't        dBt         dCt         dDt         dEt                Y d}/~/d}/~/ww xY w# t|        $ r Y 6w xY w)Yap$  
        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 gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.
            inbrowser: whether to automatically launch the gradio app in a new tab on the default browser.
            share: whether to create a publicly shareable link for the gradio app. 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. Can be set by environment variable GRADIO_SHARE=True.
            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 app. 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: By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.
            show_error: If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. They will also be displayed in the alert modal of downstream apps that gr.load() this app.
            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".
            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).
            width: The width in pixels of the iframe element containing the gradio app (used if inline=True)
            height: The height in pixels of the iframe element containing the gradio app (used if inline=True)
            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.
            allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve. 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. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible.
            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. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS.
            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". A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. 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"}`
            state_session_capacity: The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000.
            share_server_address: Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information.
            share_server_protocol: Use this to specify the protocol to use for the share links. Defaults to "https", unless a custom share_server_address is provided, in which case it defaults to "http". If you are using a custom share_server_address and want to use https, you must set this to "https".
            share_server_tls_certificate: The path to a TLS certificate file to use when connecting to a custom share server. This parameter is not used with the default FRP server at https://gradio.live. Otherwise, you must provide a valid TLS certificate file (e.g. a "cert.pem") relative to the current working directory, or the connection will not use TLS encryption, which is insecure.
            auth_dependency: A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.
            max_file_size: The maximum file size in bytes that can be uploaded. Can be a string of the form "<value><unit>", where value is any positive integer and unit is one of "b", "kb", "mb", "gb", "tb". If None, no limit is set.
            enable_monitoring: Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether.
            strict_cors: If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from "null". This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components.
            ssr_mode: If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.
            pwa: If True, the Gradio app will be set up as an installable PWA (Progressive Web App). If set to None (default behavior), then the PWA feature will be enabled if this Gradio app is launched on Spaces, but not otherwise.
            i18n: An I18n instance containing custom translations, which are used to translate strings in our components (e.g. the labels of components or Markdown strings). This feature can only be used to translate static text in the frontend, not values in the backend.
            mcp_server: If True, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools. If None (default behavior), then the GRADIO_MCP_SERVER environment variable will be used to determine if the MCP server should be enabled (which is "True" on Hugging Face Spaces).
        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?   r  NzTYou cannot provide both `auth` and `auth_dependency` in launch(). Please choose one.c              3  (   K   | ]
  }|d       yw)r   Nr   r  authenticables     rv   r  z Blocks.launch.<locals>.<genexpr>
       GM}Q''G   zOYou have provided an empty username in `auth`. Please provide a valid username.c              3  (   K   | ]
  }|d       yw)r_   Nr   r]  s     rv   r  z Blocks.launch.<locals>.<genexpr>
  r_  r`  zOYou have provided an empty password in `auth`. Please provide a valid password.r  rY  GRADIO_ALLOWED_PATHS,GRADIO_BLOCKED_PATHSz.`allowed_paths` must be a list of directories.z.`blocked_paths` must be a list of directories.__)r3  FGRADIO_SSR_MODEFalsetrueGRADIO_NODE_PATH)server_nameserver_port	node_path)rT  rP  rU  rX  z/mcpGRADIO_MCP_SERVERzIn order to use `mcp_server=True`, you must install gradio with the `mcp` extra. Please install it with `pip install gradio[mcp]`TzError launching MCP server: zInvalid local_url: z[Rerunning server... use `close()` to stop if you need to change `launch()` parameters.
----xxxi )http_server)r<  rj  rk  rM  rN  rO  rD  httphttpsuo   * Running on local URL:  {}://{}:{}, with SSR ⚡ (experimental, to disable set `ssr_mode=False` in `launch()`)z#* Running on local URL:  {}://{}:{}zstartup-events)verifytimeoutz Couldn't start the app because 'z' failed (code zJ). Check your network or proxy settings to ensure localhost is accessible.zIt looks like you are running Gradio on a hosted a Jupyter notebook. For the Gradio app to work, sharing must be enabled. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
GRADIO_SHAREzMonitoring URL: zmonitoring/)TNzWhen localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost.zColab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().zUColab notebook detected. To show errors in colab notebook, set debug=True in launch()zENote: opening Chrome Inspector may crash demo inside Colab notebooks.z:Setting share=True is not supported on Hugging Face Spacesz;Setting share=True is not supported in the Wasm environment)
local_host
local_portrk   rQ  rS  r_   z* Running on public URL: z
This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)zNot able to set up tunnelz:
Could not create share link. Checksum mismatch for file: r  zr
Could not create share link. Please check your internet connection or our status page: https://status.gradio.app.z,
Could not create share link. Missing file: z. 

Please check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps: 

1. Download this file: z#
2. Rename the downloaded file to: z$
3. Move the file to this location: z:* To create a public link, set `share=True` in `launch()`.u)   
🔨 MCP server (using SSE) running at: z/sse)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))portr   r  r  cacher  browserinline)launch_methodis_google_colabis_sharing_onis_spacer  ps1GRADIO_DEBUG0)gradio.routesr?   rA  r8  r  r   callablerg   r  r  r  rr  r  r  auth_messager  r  r  r  r'  ro   r  r  rc   r*  r8  r(  r  splitr  r)  rL  r   _parse_file_sizer!  r  r   r   rZ   re   r6  r  r  rI  max_thread_countr6  r   r  r  r   rX  rN   rl  r:   rV  node_processrW  r;  
server_appr<  r;   
gradio.mcpImportErrormcpGradioMCPServermcp_server_objlaunch_mcp_on_sser  r  r2  r.  r   r  r  rh   register_appgradioro  start_serverrj  rstriplocal_api_urlrk  serverr,  r   is_hosted_notebookrQ  rR  rS  rt   
startswithr)  formatset_server_apphttpx
is_successr   status_coderun_startup_eventsasynciocreate_taskrun_extra_startup_eventsr  analytics_keyr  r'  r   url_okr  r  setup_tunnelrk   r   r   r  r   error_analyticsr1   rG   r
   existsrH   rE   rF   lstrip
webbrowserr   ipython_checkIPython.displayrw  rx  ry  r  sleepjsondumpsartifactr   r  launched_analyticsr   r   flagsinteractiver\  block_threadrJ   )@ru   r  	inbrowserr  debugr  r  r  prevent_thread_lockr  rj  rk  r  r  r  rM  rN  rO  r'  r3  r8  r(  r)  r*  rP  ro   rQ  rR  rS  rT  r!  r  rU  rV  rW  rX  r  r  rY  rZ  r?   allowed_paths_envitemblocked_paths_envrR  mcp_subpathr  r   r  r  ro  r  resp	share_envr  
parsed_urllinkrw  rx  ry  r  coder   is_in_interactive_modes@                                                                   rv   r  zBlocks.launch	  s   P 	&,,#{{MMO ;f  TNtAw.tAw-DIDI99Xdii0GTYYGGe GTYYGGe )$
($&<#ZZ^^,>CDN&DN !.D "

/Er J$%)->-D-DS-I&%)DJJL&" &("!.D "

/Er J$%)->-D-DS-I&%)DJJL&" &("$,,d3MNN$,,d3MNN$$&"33MB==++- 399$"$UYYKr 2EI3 58K5??$D0S&'2$5) !!  ' YY0':@@BfL 	 ==ZZ^^"**<*<B-/DN " 0 )"nn ED!4#4dn JNMD!MDNT5F &4S^^+!#]]&
 	
$( !6)(;WEKKMQWWJ!
	>&,jj&@&@&F###55OO[$.. #' **,??dnnc2 #6t~~6F!GHHr !!##	 ''1.  ,, + + +!-)= -   +D&DN$(NN$9$9#$>#?
|1!MD*D DK"DO!--/DM&+&>&>&@D#(<D%)> *.: & 1MD- $D >>,,W5  M
 %%dmmE }} F> 
 ahht}}d.>.>@P@PQRKK&&t7%% yy))*.9% 
 #:488*OTXTdTdSe  fp  q  '') ##D$A$A$CD=}} 7 7 D "
"
IIn5	(Y__->&-H!%DJDJ"4>>"2+dhh>T>T=UV "3l!B!
 &&%%dnn5JJ g  == ^ k ::[ ::}}P #
!!Q #
::">>) * 7 7#'#3#3#'#3#3$($4$4-1-F-F595V5V!I "*)!4J%/335
12F&DN 1$..1ABC l* !3!3RS!DN??<T^^=it~~OdOdehOi<jjklwl~l~  @C  mD  lE  EI  J Z//%)ZZDNN4>>DOOD! >((*F4EE::$..(//?

4( )//?#,T^^,<Idjj\Q[\`\g\g[h  ia  b H ]]0 [aa!ZZ(8(89!ZZ_"jj4#zz$++6"jj/ b 1D@  *$/H#,T^^,<Idjj\Q[\`\g\g[h  ia  b H !)! 4,e4.7X#'==!% MM5		D ((t4!%gc5#)):O:O&P!Q 299^S12a7&& (. #** T__dnndnnMNNm&&|  ! X  >"'8<=>\  ))--.IJ!%"
a!67UVaUbbcd +&--/ N G}  U]  ^h  ]i  iM  N]  M^  ^C  DQ  CR  Sl  sq   7v )v%v* Aw B)w5 (A7z/  D%z/ *	w3v??w	w2w--w25	z,>B#z''z,/	z<;z<c           	        d}|d}|j                  dd       | j                  /|j                  d| j                          |j                          nF| j                  r/|j                  d| j                          |j                          nt        d      |~d}| j                  e|j                  d	|j                  d
| j                  z   dz   t        | j                        z   dz   t        | j                        z   dz         i       nt        d       |Gd}| j                  |j                  d| j                         n|j                  d| j                         | j                  r|rd|i}t        j                  |       yyy)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
        rY  NCometMLzCreated fromr  zgradio: zPlease run `launch()` first.WandBzGradio panelz<iframe src="rz  r{  z" frameBorder="0"></iframe>zAThe WandB integration requires you to `launch(share=True)` first.MLFlowzGradio Interface Share LinkzGradio Interface Local Linkintegration)	log_otherr  log_textr0  r  r   logHtmlrh   r  r  r2  	log_paramr  r   integration_analytics)ru   comet_mlwandbmlflowanalytics_integrationr   s         rv   r  zBlocks.integrate  s    !#$-!~x8~~)!!HT^^,<"=>!!HT^^,<"=> !?@@$+!~~)		&

+"nn-)* "$**o. +	+
 "$++./ <<)
 W $,!~~)  !>O  !>O!!&;!#89D++D1 '<!rx   c                   	 t         j                  r4| j                  j                          | j                  j                          | j                  j                          d| _        | j                  j                  j                          | j                  r| j                  j                          d| j                  _        |rt        d| j                          yy# t        t        f$ r Y yw xY w)zL
        Closes the Interface that was launched and frees the port.
        Fz Closing server running on port: N)r   r  rI  _cancel_asyncio_tasksr  closer  r<  
stop_eventrp   r  startup_events_triggeredr2  rk  r   OSError)ru   verboses     rv   r  zBlocks.close  s    	!! 113557KK#DOHH##%{{!!# 16DHH-89I9I8JKL ( 		s   CC C0/C0c                    	 	 t        j                  d       # t        t        f$ rO t	        d       | j
                  r| j
                  j                          t        D ]  }|j                           Y yw xY w)z,Block main thread until interrupted by user.g?z7Keyboard interruption in main thread... closing server.N)	r  r  KeyboardInterruptr  r2  r  r  rI   kill)ru   tunnels     rv   r  zBlocks.block_thread  sf    	

3 !7+ 	KL{{!!#) 		s    AA76A7c                    | j                   j                          d| j                   _        d| _        | j	                          y)zGEvents that should be run when the app containing this block starts up.FTN)rI  r  stoppedr  r  r|   s    rv   r  zBlocks.run_startup_events  s1    #rx   c                P   K   | j                   D ]  } |        d {     y 7 wrz   )r  )ru   startup_events     rv   r  zBlocks.run_extra_startup_events  s)     !66 	"M/!!	"!s   &$&c                   | j                   }i i d}| j                  j                         D ]  }|j                  r|j                  du r|s|j
                  s.g g |j
                  d}t        j                  |j                        }t        j                  |j                        \  }}|r||d<   d}	|j                  }
t        |
      D ]  \  }}|d   D ]  }|d   |j                  k(  s n d}	 n|d   d	   }| j                  |d      j                  rO|d   j                  d
d|j                         }| j                  |d         }t!        |t"        j$                        st'        |d      |j                  d|j                  d            }|j)                         }t+        j,                  |      }|j                  r!|t/        |      k  r||   d   dvr	||   d   }nd| }|d   j                  d      d}|d   d   }n3|j                  r#|t/        |      k  r||   d   r||   d   d}d}nd}d}|d   j1                  |||||||j                  dd      d|j3                         |d        |j4                  }|D ]  }|d   D ]  }|d   |j                  k(  s n d}	 n|d   d	   }| j                  |d      j                  rK|d   j                  d
d|j                         }| j                  |d         }t!        |t"        j$                        st'        |d      |j                  d|d         }|j)                         }t+        j,                  |      }|d   j1                  ||||j                  dd      d|j3                         d        |	r||d   d |j                   <    |S )!z
        Gets the information needed to generate the API docs from a Blocks.
        Parameters:
            all_endpoints: If True, returns information about all endpoints, including those with show_api=False.
        )named_endpointsunnamed_endpointsF)r   returnsr8  descriptionr   rf   Tr   r   label
parameter_z is not a Componentr  r  r   )r,  r  result_callbacksparam_rV   Nr_      r   additional_descriptionrY  )r  r  )r  parameter_nameparameter_has_defaultparameter_defaultr  python_typerw  example_inputvalue_r  r  )r  r  r  rw  r  rD  )r   r}  r   r  r,  r8  r   get_function_paramsget_function_descriptionr   r  re   r   r   rc   r<  rg   r   rQ   r:  r  r   json_schema_to_python_typer  r   
capitalizer!  )ru   all_endpointsr   r  r  dependency_infofn_infor  r   skip_endpointr   rp  input_blockrw  r  r  r;  infoexampler  r  r  r  r!  rc  s                            rv   get_api_infozBlocks.get_api_info  s-    02L((//# s	QB55BKK50  !KK0O
 //6G";;BEEBNK1<.!MYYF&/&7 @"{!'!5 I +//9 %)M )&1;;y/88!'*..w*[__DU8VW)))D/:!$
(<(<=#th.A$BCC }}%8)--
:ST--/*EEdK EEG,q)GH &-U^A%6N'-eW%5N W%))'2>,0)(1'(:7(C%EEG,q)q)1,0)(,%,1)(,%-44!&*81F-> $$/+/884Lb+Q( &*__%6)0e@D jjG !'!5 I !%%/ %)M )&1;;y/88!'*..w&8HI)))D/:!$
(<(<=#th.A$BCC }}%99Z;PQ--/*EEdK	*11!& $$/+/88M2+F( &*__%6
#: !AP*+a},=>gs	Qj rx   c           	        g }|D ]  }t        |t              r|n|d   }t        |t              r|n|d   }| j                  |      }|R|t        D cg c]   }t        |t              r|j
                  n|" c}v rt        j                  }nt        d| d      t        ||      }|j                  |        |S c c}w )Nr   r_   zCannot find Block with id: z) but is present as a target in the config)rg   r\  rc   r   r/   r  r!   r   r   r   r   )	rM  r  r  target_eventsr  	target_idr  rR  events	            rv   rZ  zBlocks.get_event_targets  s      	(F #-VS"9vayI$.vs$;J$((3E}!." )35-(HE$$eS"  $..E$5i[@ij  E:.E  '%	(& "s   %B<c                   t               rt        d      |rF|j                  d      }t        j                  d      }|j                  |      st        d| d      |t        v rt        d| d      |U|j                         j                  dd	      }d
j                  |D cg c]  }|j                         s|d	k(  s| c}      }|t        v s|| j                  D cg c]  }|d   	 c}v r.d|z   }|t        v r|| j                  D cg c]  }|d   	 c}v r.| j                  j                  ||f       || _        | S c c}w c c}w c c}w )a  
        Adds a new page to the Blocks app.
        Parameters:
            name: The name of the page as it appears in the nav bar.
            path: The URL suffix appended after your Gradio app's root URL to access this page (e.g. if path="/test", the page may be accessible e.g. at http://localhost:7860/test). If not provided, the path is generated from the name by converting to lowercase and replacing spaces with hyphens. Any leading or trailing forward slashes are stripped.
        Example:
            with gr.Blocks() as demo:
                name = gr.Textbox(label="Name")
                ...
            with demo.route("Test", "/test"):
                num = gr.Number()
                ...
        zzYou cannot create a route while inside a Blocks() context. Call route() outside the Blocks() context (unindent this line).rD  z#^[a-zA-Z0-9-._~!$&'()*+,;=:@\[\]]+$zPath 'z' contains invalid characters. Paths can only contain alphanumeric characters and the following special characters: -._~!$&'()*+,;=:@[]zRoute with path 'z' already exists r  rY  r   r   )r#   r   r  recompilematchr=   r   replacer  isalnumr  r   r   )ru   r   r   valid_path_regexletterr   s         rv   routezBlocks.route  sU     M  ::c?D!zz*PQ#))$/ TF  #j  k  ?"06FGHH<::<''S1D77&*PFfnn.>&C-PD o%djj1Qd$q'1Q)Q:D o%djj1Qd$q'1Q)Q

4,'  Q1Q1Qs   &EE#EE)NNr   r  NNNNNFFN)r  zTheme | str | Noner  r  r  rh   r!  zstr | I18nDatar  r   r-  (str | Path | Sequence[str | Path] | Noner-  r^  r  r   r.  r  r  r   r  r   r  ztuple[int, int] | None)r   dict[int, Component | Block])rV   r  )r   zdict[int, BlockFunction])rf   r\  r   Component | BlockContext)r   r(   r}  zlist[Callable]r]   rh   r   r  )r  zCallable[..., Any]r   None)r   )r  r\  r   r   )r  r\  r,  r   )NNNNFN)r  BlockFunction | intr  	list[Any]r  zAsyncIterator[Any] | Noner  Request | list[Request] | Noner  r   r  EventData | Noner  r   r  SessionState | None)r  r\  r   r  r   r  )r  r\  r!  r  r   r  )r  r  r   r  )F)r  r  r   r  r  r  r  r   )r  r  rt  zAny | list[Any])r  r  rt  list | dictr  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  )
NNNNNNTFFN)r  r  r   r  r  r  r  r  r  zAsyncIterator | Noner  r   r  r   r  r  r  r   r  r   r  r   r*  r   r   r   )r  r  r  r  r   ztuple[list[int], list])r   r(   )r3  r   rz   r  )rB  NN)rJ  zfloat | Literal['auto']r  r  rF  r   r@  zint | None | Literal['not_set'])NFNFr  NNFFNN)Pr  r  r  r   r  r  r  r   r  r\  r  zKCallable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | Noner  r   r  r   r  r   rj  r   rk  r   r  r\  r  z	int | strr  r   rM  r   rN  r   rO  r   r'  r   r3  r   r8  r   r(  r   r)  r   r*  r   rP  zdict[str, Any] | Nonero   r\  rQ  r   rR  zLiteral['http', 'https'] | NonerS  r   rT  z.Callable[[fastapi.Request], str | None] | Noner!  zstr | int | Noner  r  rU  r   rV  r   rW  r   rX  r  r  r  r  r  rY  r   rZ  zI18n | Noner   ztuple[App, str, str]r  )r  ModuleType | Noner  r  r   r  T)r  r   r   r  )r   r  )r  r   r   zAPIInfo | None)rM  zdict[int, Block]r  r  r  rh   r   r  )r   rh   r   r   r   r  )6r   r   r   __doc__rw   r   r   setterr}  r<  rA  r   rd  rI  rK  rn  r  rY   r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r   r.  r6  r  r  r>  r   r5  rL  r   r  r  r  r  r  r  r  r  r  rZ  r  __classcell__)r   s   @rv   r  r  4  s    H %))- (>B)-?C! /3T!T 'T 	T
 T T <T 'T T =T T T -Tl * * ]]+ + ' ' ? ? ` ` ` 	`
 
` `D" 
 
!
F<|G 12$ 0!l /337#'+"'%)[
%[
 #[
 ,	[

 1[
 [
 %[
  [
 #[
z4" N $-- - #	-
 -^+Zii !i #	i
 
ib !%33 3 !	3
 3 3 3 
3x $     !	 
       
 L &*26)-#'#'+"&## $]%] ] #	]
 0] '] !] ] %]  ] ] ] ] 
]~1%1.A1	1"
"4lD0* Z 7= $#	' FO'3' ' 	' $C' 'RY  #! #'$) "&"&QO  !*."&#'+/'///*.*. $,0&++/AE37JN*.)- '+ $ $"& WQOQO QO 	QO
 QO QO XQO !QO "QO QO  QO  QO  !QO" #QO$ (%QO&  'QO( !)QO* )+QO, -QO. /QO0 1QO2 (3QO4 (5QO6 7QO8 *9QO: !$;QO< )=QO>  ??QO@ '1AQOB HCQOD (EQOF 'GQOH IQOJ %KQOL MQON OQOP QQOR  SQOT UQOV WQOX 
YQOj #'$(	52 !52 "	52
 
52n:	"~@ *6:EH	 2 Z% %rx   r  )	metaclassr  )rR  r  rj  r   r  r   )rs  r  rt  r   r   r  )
__future__r   r  r  r   r   r   r  r  r  r  ri   r  r   r	  r  r  r  collectionsr   collections.abcr   r   r   r   r	   pathlibr
   rN  r   typingr   r   r   r   r   urllib.parser   r   r  fastapir  r   gradio_clientr   r   gradio_client.documentationr   groovyr   r  r   r   r   r   r   r   r   gradio.blocks_eventsr   r   r    gradio.contextr!   r"   r#   r$   r%   gradio.data_classesr&   r'   r(   r)   r*   r+   r,   r-   gradio.eventsr.   r/   r0   gradio.exceptionsr1   r2   r3   r4   gradio.helpersr5   r6   r7   gradio.i18nr8   r9   gradio.node_serverr:   gradio.route_utilsr;   r<   r  r=   r>   r?   r@   gradio.state_holderrA   rB   gradio.themesrC   r  rD   r  gradio.tunnelingrE   rF   rG   rH   rI   gradio.utilsrJ   rK   rL   rM   rN   rO   rP   rF  r  gradio.components.baserQ   gradio.renderablerR   Base
MonochromeSoftGlassOriginCitrusOceanr   rS   __annotations__rU   r   r  rl  ry  r{  r  )r4  s   0rv   <module>r>     s?   "       	  	   
     # M M   ; ; -    ! / 0 	 	 	 I H 	 	 	 
  > = & 0 6 @ @ 9 1 -   
 0,
 		%	 FFAI%! i iX	a5 aHM
 M
b MQ#26EI2)-6b8 b8J 
(G[&(;b"\<: b" <b"c  F%s   I/ 6I=/I:9I: