
    ;3h;                       d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Zddl
ZddlZddl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m Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddlm,Z, dd	l-m.Z. dd
l/m0Z0 ddl1m2Z2m3Z3 ddlm4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<Z<ddl=m>Z? ddl@Z@ddlAZAddlBmCZC ddlDmEZE ddlFmGZG ddlHZHddlImJZJ ddlKmLZLmMZMmNZNmOZO ddlPmQZQmRZR e4rddlSmTZTmUZU ddlVmWZW ddlXmYZYmZZZ ddl[m\Z\  eGd      Z] e9d      Z^dydZ_dzdZ`d{dZa G d de      Zb G d deb      Zc G d  d!ed      Ze eed"      Zfd|d#Zgd}d$Zhd~d%Zidd&Zjdd'Zkdd(Zldd)Zmdd*Zndd+Zodd,Zpdd-Zqej                  j                  ej                  j                  eHj                        d.      Zvdyd/Zwdd0Zxdd1Zy	 d	 	 	 	 	 dd2Zz	 d	 	 	 	 	 	 	 dd3Z{dd4Z|dd5Z}d6 Z~dd7Zdd8Zd9 Z G d: d;      Zd< Ze+dd=       Ze+d>        Zdd?Zdd@ZddAZddBZdC Z	 	 	 	 d	 	 	 	 	 	 	 	 	 ddDZ	 	 	 	 	 	 	 	 	 	 	 	 ddEZddFZddGZ	 	 	 	 ddHZdI ZdJ ZddKZ G dL dMe      Z G dN dO      ZdP ZddQZddRZ eC       ddS       ZddTZddUZ ej8                  dVej:                        ZddWZddXZ G dY dZe      Zd[ Zdd\Z e9d]      Z e9d^      Z G d_ d`e"e6eef         ZddaZdb ZdydcZdddZddeZdf Zdg Zdh ZddiZ G dj dk      ZddlZddmZdn Z	 	 	 	 	 	 ddoZ G dp dqe(      ZddrZ	 	 	 	 	 	 	 	 	 	 ddsZdt ZdduZddvZdw ZddxZy)zHandy utility functions.    )annotationsN)ABCabstractmethod)OrderedDict)CallableHashableIterableIteratorMutableMappingSequence)contextmanagerwraps)BytesIO)Path)
ModuleTypeNoneType)TYPE_CHECKINGAnyGenericLiteralOptionalTypeVarget_args
get_origin)document)AppError)	ParamSpec)get_blocks_context)BlocksConfigDictDeveloperPathFileDataUserProvidedPath)ErrorInvalidPathError)BlockContextBlocks	Component)AppRequest)SessionStatePTc                     	 t        j                  t        d      j                  d      j	                         } t        j                  |       }|j                  dd      }|S # t        $ r Y yw xY w)Nzpackage.jsonutf-8version )	pkgutilget_data__name__decodestripjsonloadsget	Exception)package_json_datapackage_datar1   s      L/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/utils.pyget_package_versionr?   U   sj    X~6==gFLLN 	 zz"34""9b1 s   AA" "	A.-A.c                 r    	 t        j                          t        j                         S # t        $ r Y yw xY w)zGet asyncio.Lock() without fear of getting an Exception.

    Needed because in reload mode we import the Blocks object outside
    the main thread.
    N)asyncioget_event_loopLockRuntimeError     r>   safe_get_lockrG   a   s1     ||~    '* 	66c                 r    	 t        j                          t        j                         S # t        $ r Y y w xY wN)rA   rB   EventrD   rE   rF   r>   safe_get_stop_eventrL   n   s1     }} rH   c                  0    e Zd Zeedd              ZddZy)BaseReloaderc                     y rJ   rE   selfs    r>   running_appzBaseReloader.running_appw   s     	rF   c                P   | j                   j                  sJ | j                   j                  j                  |_        d|_        | j                   j                  j                  |_        d|_        | j                   j                  j                  |       || j                   _        y )NT)rR   blocks_queuehas_launchedmax_file_size
is_runningstate_holderreset)rQ   demos     r>   swap_blockszBaseReloader.swap_blocks|   s    &&&& &&--44 !--44BB%%++D1"&rF   Nreturnr*   r[   r'   )r5   
__module____qualname__propertyr   rR   r\   rE   rF   r>   rN   rN   v   s!      	'rF   rN   c                  z     e Zd Z	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZed	d       Zd
dZddZdddZd fdZ	 xZ
S )SourceFileReloaderc                    t         |           || _        || _        || _        || _        || _        t        |      | _        || _	        y rJ   )
super__init__app
watch_dirswatch_module_name
stop_event	demo_namer   	demo_filewatch_module)	rQ   rh   ri   rj   rm   rn   rk   rl   	__class__s	           r>   rg   zSourceFileReloader.__init__   sG     	$!2$"i(rF   c                    | j                   S rJ   )rh   rP   s    r>   rR   zSourceFileReloader.running_app   s    xxrF   c                8    | j                   j                          S rJ   )rk   is_setrP   s    r>   should_watchzSourceFileReloader.should_watch   s    ??))+++rF   c                8    | j                   j                          y rJ   )rk   setrP   s    r>   stopzSourceFileReloader.stop   s    rF   c                d    || j                   _        | j                   xj                  dz  c_        y )N   )rh   change_typechange_count)rQ   ry   s     r>   alert_changezSourceFileReloader.alert_change   s#    *"rF   c                    | j                   j                  }t        |   |       |rt	        ||       |j                         |_        | j                  d       y )Nreload)rR   rT   rf   r\   reassign_keysget_config_fileconfigr{   )rQ   r[   
old_blocksro   s      r>   r\   zSourceFileReloader.swap_blocks   sL    %%,,
D!*d+**,(#rF   )r[   )rh   r*   ri   	list[str]rj   strrm   r   rn   r   rk   zthreading.Eventrl   r   r^   Noner]   r^   boolr^   r   )r}   )ry   zLiteral['reload', 'error']r_   )r5   r`   ra   rg   rb   rR   rs   rv   r{   r\   __classcell__ro   s   @r>   rd   rd      s      )) ) 	)
 ) !) $) ) 
)&  ,#$ $rF   rd   c                  "    e Zd ZddZd ZddZy)DynamicBooleanc                $    t        |      | _        y rJ   r   valuerQ   r   s     r>   rg   zDynamicBoolean.__init__       %[
rF   c                    | j                   S rJ   r   rP   s    r>   __bool__zDynamicBoolean.__bool__   s    zzrF   c                $    t        |      | _        y rJ   r   r   s     r>   ru   zDynamicBoolean.set   r   rF   N)r   int)r5   r`   ra   rg   r   ru   rE   rF   r>   r   r      s    !!rF   r   Tc                   t        | d      5 }|j                         }ddd       t        j                        }dd}t        j                  |      D ]X  } ||      st        |t        j                        sJ t        j                  |j                  |j                        g|_
        Z t        || d      }|S # 1 sw Y   xY w)	zParse the file, remove the gr.no_reload code blocks, and write the file back to disk.

    Parameters:
        file_path (str): The path to the file to remove the no_reload code blocks from.
    r0   )encodingNc                   t        | t        j                        xr, t        | j                  t        j                        xr t        | j                  j
                  t        j                        xr | j                  j
                  j                  dk(  xr t        | j                  j                        dk(  xr t        | j                  j                  d   t        j                        xrY t        | j                  j                  d   t        j                        xr& | j                  j                  d   j                  dk(  S )z*Find the if __name__ == '__main__': block.r5   rx   r   __main__)
isinstanceastIftestCompareleftNameidlenopsEqcomparatorsConstants)exprs    r>   _is_if_name_mainz8_remove_if_name_main_codeblock.<locals>._is_if_name_main   s     tSVV$ 9499ckk29499>>38849 		!!Z/9 DIIMM"a'	9
 499==+SVV49 499003S\\B9 		%%a(**j8		
rF   )lineno
col_offsetexec)filenamemode)r   zast.ASTr^   r   )openreadr   parsewalkr   r   Passr   r   bodycompile)	file_pathfilecodetreer   nodecode_removeds          r>   _remove_if_name_main_codeblockr      s     
i'	* dyy{ 99T?D
  SD!dCFF+++QRDIS 4)&AL5 s   C  C	c                    t         j                  j                         D ]'  \  }}|dvst        |dd       t	        |       k(  s%|c S  y )N>   r   __mp_main____file__)sysmodulesitemsgetattrr   )source_filer   vs      r>   _find_moduler      sS    !!# 1//GAz44PTWU
 5
 H	
 rF   c                   t         j                  d       ddlm} d|_        dfd}dfd| j
                  D cg c]  }t        |       c}ddl}D ]'  }|j                  j                  dt        |             ) i | j                  }t        t        | j                              }ddlm} d|_        t#        ||j$                         ||j&                  | j(                  <   | j+                         r8 |       }|rt-        d	|        	 |j.                  d
k(  rt        t        |            }	|| j                  k7  rht1        |      }
|
r[t#        |	|
j$                         |j&                  |
j2                  j5                  d      d      }||
k7  rt7        j8                  |       t        t        | j                              }t#        ||j$                         tO        || jP                        }| jS                  |       i tU        jV                  d       | j+                         r7yyc c}w # t:        $ r}t-        d| j(                   d       t=        |t>              r|j@                  rtC        jD                          i | jG                  d       tC        jH                         | jJ                  _&        Y d}~d}~ww xY w)ziWatch python files in a given module.

    get_changes is taken from uvicorn's default file watcher.
    Fr   )reload_threadTc                             D ]?  } 	 | j                         j                  }j                  |       }||| <   7||kD  s=| c S  y # t        $ r Y Nw xY wrJ   )statst_mtimeOSErrorr:   )r   mtimeold_timeiter_py_filesmtimess      r>   get_changeszwatchfn.<locals>.get_changes   sr    !O 	D		,, zz$'H$t!	   s   A	AAc               3     K   D ]d  } t        | j                  d            D ]  }|j                           t        | j                  d            D ]  }|j                           f y w)Nz*.pyz*.css)listrglobresolve)
reload_dirpathreload_dirss     r>   r   zwatchfn.<locals>.iter_py_files  sl     % 	%JZ--f56 %lln$%Z--g67 %lln$%	%s   A+A.N)ContextzChanges detected in: z.py.z
Reloading z& failed with the following exception: errorg?)r^   zPath | None)r^   zIterator[Path]),	NO_RELOADru   gradio.cli.commands.reloadr   running_reloadri   r   r   r   insertr   rn   r   rm   gradio.contextr   r   r   __dict__r   rj   rs   printsuffixr   r5   split	importlibr}   r;   r   r$   print_exception	traceback	print_excr{   
format_excrh   reload_error_messager   rl   r\   timesleep)reloaderr   r   dir_r   moduleno_reload_source_coder   changedchanged_in_copychanged_moduletop_level_parentchanged_demo_filer   r[   r   r   r   s                  @@@r>   watchfnr      sf    MM%
 9#'M % +3*=*=>$4:>K &3t9%& F ""F:3x?Q?Q;RS 'GJ	0.4CKK**+



!-)'34# >>U*&DS\&RO("4"44)5g)>) .2I2IJ/2{{ . 7 7 = =c B1 E0,  0>A ) 0 01A B$B**+%! &8 68#5#56D  &F

4W 


!
!' ?b  	 !;!; <<bc "%/53H3H'')%%g.4=4H4H4J1	s    H8CH= =	KA?KKc                x    dd}	  ||        ||      k(  S # t         $ r 	 | |k(  cY S # t        $ r Y Y yw xY ww xY w)z
    Deep equality check for component values.

    Prefer orjson for performance and compatibility with numpy arrays/dataframes/torch tensors.
    If objects are not serializable by orjson, fall back to regular equality check.
    c                n    t        j                  | t         j                  t         j                  z        S )N)option)orjsondumpsOPT_SERIALIZE_NUMPYOPT_PASSTHROUGH_DATETIME)as    r>   
_serializezdeep_equal.<locals>._serialize\  s*    ||--0O0OO
 	
rF   F)r   r   r^   bytes)	TypeErrorr;   )r   br   s      r>   
deep_equalr  T  sN    
!}
1-- 	6M 		s     	9(9	5959c                    ddl m |j                  D cg c]  }|j                  |j                   c}	 	 	 	 dfd | |       y c c}w )Nr   )r&   c           	        t        |j                        D ]  \  }}| r(|t        | j                        k  r| j                  |   }nd }|j                  r|j                  |j                  k(  rD|B|j                  vr4t        t        |dd       t        |dd             r|j                  |_        nd|j                   d|_        t        |      st        |      r#|j                  |j                  k(  r
 ||        d |        y )Nr   __)		enumeratechildrenr   keyro   r  r   _idr   )old_contextnew_contexti	new_block	old_blockr&   assigned_keysreassign_context_keyss        r>   r  z,reassign_keys.<locals>.reassign_context_keysr  s     &k&:&:; 	;LAyq3{';';#<<'003	 	}}$''9+>+>>!-!]:"	7D9	7D9
 %.MMIM&(r$:IM)\2y,7!++y/B/BB))Y?)$	:5	;rF   )r  zBlockContext | Noner  r&   )gradio.blocksr&   r  r	  )r   
new_blocksblockr&   r  r  s      @@@r>   r~   r~   k  sW    *  *22eii6K		M;(;7C;> *j1Gs
   AAc                 p    d} 	 ddl m}  |       }dt        |      v rd} | S # t        t        f$ r Y | S w xY w)zf
    Check if interface is launching from Google Colab
    :return is_colab (bool): True or False
    Fr   get_ipythonzgoogle.colabT)IPython.core.getipythonr  r   ImportError	NameError)is_colabr  
from_ipynbs      r>   colab_checkr    sN    
 H7 ]
S_,H O # Os   " 55c                     t        t        j                  j                  d      xs t        j                  j                  d            S )z^
    Check if Gradio app is launching from a hosted notebook such as Kaggle or Sagemaker.
    KAGGLE_KERNEL_RUN_TYPEz/home/ec2-user/SageMaker)r   osenvironr:   r   existsrE   rF   r>   is_hosted_notebookr#    s8     


/0 	677>>45 rF   c                 V    d} 	 ddl m}  |       d} | S # t        t        f$ r Y | S w xY w)zo
    Check if interface is launching from iPython (not colab)
    :return is_ipython (bool): True or False
    Fr   r  T)r  r  r  r  )
is_ipythonr  s     r>   ipython_checkr&    sE    
 J7=$J  # s    ((c                 ^    t        j                  d      dk(  rt        j                  d      S y )NSYSTEMspacesSPACE_IDr   getenvrE   rF   r>   	get_spacer-    s%    	yyh&yy$$rF   c                 2    t        j                  d      dk(  S )NSPACES_ZERO_GPUtruer+  rE   rF   r>   is_zero_gpu_spacer1    s    99&'611rF   c                   	 t         j                  j                  |       }t        |j                  |j
                  |j                  g      }|xr |j                  dv }|s| S 	 t        j                  | d      }|j                  t        j                  j                  k(  r|j                  } | S # t        $ r d}Y ^w xY w# t        j                  t        j                  t        j                   f$ r Y | S w xY w)N)httphttpsF   )timeout)urllibr   urlparseallschemenetlocr   
ValueErrorhttpxr:   status_codecodesOKtext
InvalidURLRequestErrorTimeoutException)articleresultis_urlresponses       r>   download_if_urlrI    s    &&w/fmmV]]FKK@A>FMM->> 99Wa05;;>>1mmG N   e00%2H2HI Ns%   AB0 $A
C 0B>=B>2C76C7zhash_seed.txtc                    	 t         j                  j                  t              r7t	        t              5 } | j                         j                         cd d d        S t	        t        d      5 } t        j                         j                  }| j                  |       |cd d d        S # 1 sw Y   y xY w# 1 sw Y   y xY w# t        $ r! t        j                         j                  cY S w xY w)Nw)r   r   r"  HASH_SEED_PATHr   r   r7   uuiduuid4hexwriter;   )jseeds     r>   get_hash_seedrS    s    
 77>>.)n% (vvx~~'( ( nc* azz|'' ( (    zz| sR   2B? B'	B? B? ,1B3	B? 'B0,B? 0B? 3B<8B? <B? ?'C)(C)c                    t        j                  |       }|j                  j                         D cg c]6  }|j                  t         j
                  j                  ur|j                  nd 8 c}S c c}w rJ   )inspect	signature
parametersvaluesdefault	Parameterempty)funcrV  r   s      r>   get_default_argsr]    sc    !!$'I %%,,. YYg&7&7&=&==		4G  s   ;A0c           	         	 t        j                  |       S # t        $ r t        | t              r?| j                         D ci c]  \  }}t        |      t        |       nc c}}w c}}cY S t        | t              r!| D cg c]  }t        |       nc c}w c}cY S t        | t              rt        d | D              cY S t        | t              r!| D ch c]  }t        |       nc c}w c}cY S t        j                   |       cY S w xY w)Nc              3  2   K   | ]  }t        |        y wrJ   )safe_deepcopy).0items     r>   	<genexpr>z safe_deepcopy.<locals>.<genexpr>  s     =t,=   )
copydeepcopyr;   r   dictr   r`  r   tupleru   )objr	  r   rb  s       r>   r`  r`    s    "}}S!! "c4 KN99;=GS%c"M%$88   T"478DM$'888U#====S!478DM$'88899S>!"sK    ,DA#"D/DB	D "DDC+*	D5DDc                6    t        j                          t        j                        t        j                  t        j                                t        j                  t        j                              |D ]  } |   |   k7  st        d|        t         d         t        d         k7  rt        d       fdfdd v rBdvrt        d       d   j                  dg       }d   j                  dg       } ||       d	 v rd	vrt        d
      t         d	   d	   d      D ]  \  }}t        |j                  d      |j                  d      d      D ]  \  }}	 |d   |	d           t        |j                  d      |j                  d      d      D ]  \  }
} |
|        t        |j                  d      |j                  d      d      D ]  \  }} ||        ||k7  st        | d|        y)a  Allows you to test if two different Blocks configs produce the same demo.

    Parameters:
    config1 (dict): nested dict with config from the first Blocks instance
    config2 (dict): nested dict with config from the second Blocks instance
    root_keys (Tuple): an interable consisting of which keys to test for equivalence at
        the root level of the config. By default, only "mode" is tested,
        so keys like "version" are ignored.
    zConfigs have different: 
componentsz# of components are differentc                    t        t         fdd               }t        |      dk(  rt        d        |d   }t        t        fdd               }t        |      dk(  rt        d       |d   }t	        j
                  |      }|j                  d       t	        j
                  |      }|j                  d       ||k7  rt        | d|       y )Nc                    | d   k(  S Nr   rE   )c
config1_ids    r>   <lambda>z[assert_configs_are_equivalent_besides_ids.<locals>.assert_same_components.<locals>.<lambda>"      1T7j#8 rF   rk  r   z!Could not find component with id c                    | d   k(  S rn  rE   )ro  
config2_ids    r>   rq  z[assert_configs_are_equivalent_besides_ids.<locals>.assert_same_components.<locals>.<lambda>&  rr  rF   r    does not match )r   filterr   r<  re  rf  pop)rp  rt  c1c2config1config2s   ``  r>   assert_same_componentszIassert_configs_are_equivalent_besides_ids.<locals>.assert_same_components!  s    &8',:OPQr7a<@MNNU&8',:OPQr7a<@MNNU]]2
t]]2
t8t#3B4899 rF   c                    t        | |d      D ],  \  }} |d   |d          d|v sd|v s |d   |d          . y )NFstrictr   r  )zip)	children1chidren2child1child2r|  same_children_recursives       r>   r  zJassert_configs_are_equivalent_besides_ids.<locals>.same_children_recursive1  sV    !)XeD 	PNFF"6$<>V#zV';'z(:F:<NO	PrF   layoutz:The first config has a layout key, but the second does notr  dependenciesz@The first config has a dependencies key, but the second does notFr~  targetsr   inputsoutputsru  T)
re  rf  r8   r9   r   r<  r   r:   r  rw  )rz  r{  	root_keysr	  r  	children2d1d2t1t2i1i2o1o2r|  r  s   ``            @@r>   )assert_configs_are_equivalent_besides_idsr  	  s2    mmG$GmmG$GjjG,-GjjG,-G ?3<73<'7u=>>? 7< !S)>%??899: P 77"L  H%))*b9	H%))*b9		95 (R  N#W^%<U
 
	>FB bffY/	1B5Q 5B&r!ube45bffX.x0@O /B&r2./bffY/	1B5Q /B&r2./Rx B4'7t!<==
	> rF   c                z    |g n|}t        | j                               D ]  \  }}||v r|r|dk(  r|| |=  | S )z=
    Delete keys whose values are None from a dictionary
    r   )r   r   )_dict
skip_value
skip_propsr	  r   s        r>   delete_noner  T  sX     ")zJ5;;=) 
U*#.]c
 LrF   c                ,    t        |       dk(  r| d   S | S )Nrx   r   )r   )_lists    r>   resolve_singletonr  e  s    
5zQQxrF   c                 p   dd l } | j                  j                  j                         | j                  j
                  j                         z   }g }|rC|j                         }|j                  |j                                |j                  |       |rC|D cg c]  }|j                  dvr| c}S c c}w )Nr   )ChatInterface	Interfacer'   TabbedInterface
NativePlot	SketchBox)
gradiork  r)   __subclasses__rT   r&   rw  extendappendr5   )grclasses_to_check
subclassessubclassro  s        r>   get_all_componentsr  l  s     	..0
))
 
 
/
/
1	2  J
#'') 7 7 9:(#  ::

 	
  s   B3c                 r    t               D  cg c]  } | j                  j                  d      r| ! c} S c c} w )Nzgradio.)r  r`   
startswith)class_s    r>   core_gradio_componentsr    s;     )*''	2 	  s   $4c                   ddl m} ddl m} t               D ci c]  }|j                  j                         | }}|j                  j                         D ]6  \  }}t        |t              st        ||      s$|||j                         <   8 | j                  dd      |v r|| j                  dd         S t        d|  d      c c}w )z
    Returns the component, template, or layout class with the given class name, or
    raises a ValueError if not found.

    Parameters:
    cls_name (str): lower-case string class name of a component
    Returns:
    cls: the component class
    r   Nr(   _r2   zNo such component or layout: zw. It is possible it is a custom component, in which case make sure it is installed and imported in your python session.)gradio.componentsrk  r)   r  r5   lowerr   r   r   type
issubclassreplacer<  )cls_namecomponents_moduler)   ro  rk  nameclss          r>   component_or_layout_classr    s     2+1C1EFA!**""$a'FJF&//557 +	cc4 ZY%?'*Jtzz|$+ R J.(**3344

'z 2W 	W  Gs   "Cc                X    t        j                         }|j                   | |i |      S )a?  
    Runs coroutines in background.

    Warning, be careful to not use this function in other than FastAPI scope, because the event_loop has not started yet.
    You can use it in any scope reached by FastAPI app.

    correct scope examples: endpoints in routes, Blocks.process_api
    incorrect scope examples: Blocks.launch

    Use startup_events in routes.py if you need to run a coro in background in Blocks.launch().


    Example:
        utils.run_coro_in_background(fn, *args, **kwargs)

    Args:
        func:
        *args:
        **kwargs:

    Returns:

    )rA   rB   create_task)r\  argskwargs
event_loops       r>   run_coro_in_backgroundr    s-    0 '')J!!$"7"788rF   c                J    	 t        |       S # t        $ r t               dw xY w)z;Helper for yielding StopAsyncIteration from sync iterators.N)nextStopIterationStopAsyncIterationiterators    r>   run_sync_iterator_asyncr    s+    -H~ - ",-s   
 "c                  $    e Zd ZdZddZd Zd Zy)SyncToAsyncIteratorz*Treat a synchronous iterator as async one.c                     || _         || _        y rJ   )r  limiter)rQ   r  r  s      r>   rg   zSyncToAsyncIterator.__init__  s     rF   c                    | S rJ   rE   rP   s    r>   	__aiter__zSyncToAsyncIterator.__aiter__  s    rF   c                   K   t         j                  j                  t        | j                  | j
                         d {   S 7 w)N)r  )anyio	to_threadrun_syncr  r  r  rP   s    r>   	__anext__zSyncToAsyncIterator.__anext__  s;     __--#T]]DLL . 
 
 	
 
s   >A AANr   )r5   r`   ra   __doc__rg   r  r  rE   rF   r>   r  r    s    4
rF   r  c                4   K   t        |        d {   S 7 wrJ   )anextr  s    r>   async_iterationr    s     x   s   c              #     K   t               j                         }	 t        j                  |        d t        j                  |       y# t        j                  |       w xY ww)zBContext manager that sets the working directory to the given path.N)r   absoluter   chdir)r   origins     r>   set_directoryr    sA      V__F

s   A%A A%A""A%c               #  4   K   	 d y# t         $ r Y yw xY ww)z+Context manager that suppresses exceptions.N)r;   rE   rF   r>   no_raise_exceptionr    s      s   	 	c                     t         t        t        f      r S g d}g d}t         fd|D              st         fd|D              rd    S )z
    Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.
    Reference: https://owasp.org/www-community/attacks/CSV_Injection
    )=+-@	
)z,=z,+z,-z,@z,	z,
c              3  @   K   | ]  }j                  |        y wrJ   )r  )ra  prefixr   s     r>   rc  z)sanitize_value_for_csv.<locals>.<genexpr>  s     
B5F#
Bs   c              3  &   K   | ]  }|v  
 y wrJ   rE   )ra  sequencer   s     r>   rc  z)sanitize_value_for_csv.<locals>.<genexpr>  s      J&EJ   ')r   floatr   any)r   unsafe_prefixesunsafe_sequencess   `  r>   sanitize_value_for_csvr    sZ    
 %%&6O=

B/
BBc J*:J G E7LrF   c                    g }| D ]X  }t        |t              r*|D cg c]  }t        |       }}|j                  |       =t        |      }|j                  |       Z |S c c}w )z
    Sanitizes a list of values (or a list of list of values) that is being written to a
    CSV file to prevent CSV injection attacks.
    )r   r   r  r  )rX  sanitized_valuesr   r   sanitized_values        r>   sanitize_list_for_csvr  
  sp    
  5eT"BGHQ5a8HOH##O44U;O##O45  Is   A"c                d    t        |      }| |vr| S d}|  d| }||v r|dz  }|  d| }||v r|S )zSAppends a numerical suffix to `name` so that it does not appear in `list_of_names`.rx   r  )ru   )r  list_of_namesset_of_namessuffix_counternew_names        r>   append_unique_suffixr    sc     /L<V1^,-,&aNq 01H ,& rF   c                    ddi}	 t        j                  | |d      }|j                  dv r"t        j                  | |d      j                  S |j                  S # t
        $ r Y yw xY w)Nz
User-Agentz8gradio (https://gradio.app/; gradio-team@huggingface.co)T)headersfollow_redirects)i  i  F)r=  headr>  r:   
is_successr;   )possible_urlr  head_requests      r>   validate_urlr  (  sp    WXG	zz,RVW##z199gj &&& s   AA A 	A&%A&c                N    t        | t              xr d| j                  dd      v S )Nupdate__type__r2   )r   rg  r:   )vals    r>   is_prop_updater  6  s$    c4 HXR1H%HHrF   c                    g ng nt        j                         r#t        j                          fd       }|S t	        j
                         r#t        j                          fd       }|S t        j                         r#t        j                          fd       }|S t        j                          fd       }|S )Nc                   K    | i |}	 r   	 |j                          d {   }r   | -7 # t        $ r
 r   Y y w xY wwrJ   )r  r  	r  r  r  rH  
after_argsafter_fnbefore_args	before_fnfs	       r>   asyncgen_wrapperz*function_wrapper.<locals>.asyncgen_wrapperE  sr     $)&)H{+%-%7%7%99H
 j)   :)  *-s1   A< :< A< AAAAc                 P   K   r    | i | d {   }r   |S 7 wrJ   rE   r  r  rH  r  r  r  r  r  s      r>   async_wrapperz'function_wrapper.<locals>.async_wrapperY  s9     ;'///H*%O 0s   &$&c               ?     K    | i |}	 r   	 t        |      }r   | # t        $ r
 r   Y y w xY wwrJ   )r  r  r  s	       r>   gen_wrapperz%function_wrapper.<locals>.gen_wrapperf  sg     $)&)H{+#H~H
 j) 
 %  *-s    A, A?A?Ac                 4    r    | i |}r   |S rJ   rE   r  s      r>   wrapperz!function_wrapper.<locals>.wrapperz  s-    ;'$)&)H*%OrF   )rU  isasyncgenfunction	functoolsr   rA   iscoroutinefunctionisgeneratorfunction)	r  r  r  r  r  r  r  r  r  s	   `````    r>   function_wrapperr  :  s     $+"K!)zJ!!!$			 
	  		$	$Q	'			 
	 		$	$Q	'			 
	  
		 
	 rF   c                >    fd}d }t        | |||f|      S )Nc                :   ddl m} |j                  j                  |        |j                  j                         |j
                  j                  |       |j                  j                         r&|j                  j                  j                         y y )Nr   LocalContext)r   r!  rT   ru   in_event_listenerevent_idrequestblocks_config)rT   r#  r!  r"  r$  states      r>   r  z+get_function_with_locals.<locals>.before_fn  sy    /'&&**+<=!!(+  )&&**5+>+>? rF   c                     ddl m}  | j                  j                  d       | j                  j                  d        | j
                  j                  d        y )Nr   r   F)r   r!  r"  ru   r$  r%  r   s    r>   r  z*get_function_with_locals.<locals>.after_fn  sA    /&&**51  &""&&t,rF   )r  r  r  )r  )fnrT   r#  r"  r$  r&  r  r  s      ```  r>   get_function_with_localsr)    s.    @- 
X&	 rF   c                t  K   t        j                         D cg c]  }||j                         f }}g }g }|D ]U  \  }}d|vr|j                  d      \  }}|| v s$|j	                  |       |j	                  |       |j                          W t        j                  |ddi d {    |S c c}w 7 w)N<gradio-sep>return_exceptionsT)rA   	all_tasksget_namer   r  cancelgather)task_idstasktasks	event_idsmatching_tasksr  task_idr#  s           r>   cancel_tasksr7    s     181B1B1DEdDMMO$EEEIN 
d% JJ~6h!!$'X&KKM ...
AD
AAA F Bs"   B8B1+B8AB8*B6+B8c                <    |s| j                  | d| d|        y y )Nr  r+  )set_name)r2  session_hashfn_indexr#  batchs        r>   set_task_namer=    s'    azhZHI rF   c                    g }| D ]L  t               }|st        fd|j                  j                         D              }|j	                  |       N |S )Nc              3  P   K   | ]  \  }}|j                         k(  s|  y wrJ   )
get_config)ra  r  ddeps      r>   rc  z+get_cancelled_fn_indices.<locals>.<genexpr>  s'      a#8Ms   &&)r   r  fnsr   r  )r  
fn_indices
root_blockr;  rB  s       @r>   get_cancelled_fn_indicesrF    s`     J (')
 (nn224 H h'( rF   c                    t        j                  |       st        j                  |       rnt        |       r| j                  } ni S t        j                  |       S rJ   )rU  
isfunctionismethodcallable__call__typingget_type_hints)r(  s    r>   rM  rM    sF    "!1!1"!5	"[[	  $$rF   c                    ddl m} ddlm}m} ddlm} 	 |j                  |       }|sy||t        |   fv }||t        |   |t        |   fv }t        j                  |      xr t        ||      }	|xs |	xs |S )Nr   )	EventData)OAuthProfile
OAuthToken)r+   F)gradio.helpersrO  gradio.oauthrP  rQ  gradio.routesr+   r:   r   rU  isclassr  )
r  parameter_typesrO  rP  rQ  r+   hint
is_requestis_oauth_argis_event_datas
             r>   is_special_typed_parameterr[    s    (5%}t$D'8G#455J	 L OOD)Ijy.IM66,6rF   c           	        	 t        j                  |       }t        |       }d}d}d}|j                  j                         D ]  \  }}	|	j                  |	j                  k7  }
|	j                  |	j                  |	j                  fv rt        ||      rP|
s|dz  }|dz  }]|	j                  |	j                  k(  r|}y|	j                  |	j                  k(  s|
rd|  c S  |rdn
t        |      }||k(  r$||k7  rt        j                   d| d|  d| d	       ||k  rt        j                   d
| d|  d| d	       ||k7  r&||kD  r t        j                   d| d|  d| d	       yyy# t        $ r Y yw xY w)z
    Checks if the input component set matches the function
    Returns: None if valid or if the function does not have a signature (e.g. is a built in),
    or a string error message if mismatch
    Nr   rx   z8Keyword-only args must have default values for function z	Expected z arguments for function z, received r   zExpected at least zExpected maximum )rU  rV  r<  rM  rW  r   rY  r[  kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr[  VAR_POSITIONALKEYWORD_ONLYr   warningswarn)r(  r  inputs_as_dictrV  rV  min_argsmax_argsinfinityr  paramhas_default	arg_counts               r>   check_function_inputs_matchrl    s   %%b)	 %R(OHHH ++113 
Semmu{{2::%//1L1LMM-dOD"MHAZZ5///HZZ5---kMbTRR
S $VI8I 5z!9"[STU	
 8 
*B2$kR[Q\\]^	
 8	H 4z)A"[QZP[[\]	
 !55  s   E( (	E43E4c                      e Zd Zd Zd Zy)TupleNoPrintc                     yNr2   rE   rP   s    r>   __repr__zTupleNoPrint.__repr__      rF   c                     yrp  rE   rP   s    r>   __str__zTupleNoPrint.__str__  rr  rF   N)r5   r`   ra   rq  rt  rE   rF   r>   rn  rn    s    rF   rn  c                      e Zd Zd Zd Zy)MatplotlibBackendManangerc                x    	 dd l }|j                         | _        |j                  d       y # t        $ r Y y w xY w)Nr   agg)
matplotlibget_backend_original_backenduser  )rQ   ry  s     r>   	__enter__z#MatplotlibBackendMananger.__enter__  s9    	%/%;%;%=D"NN5! 		s   *- 	99c                b    	 dd l }|j                  | j                         y # t        $ r Y y w xY wNr   )ry  r|  r{  r  )rQ   exc_typeexc_valexc_tbry  s        r>   __exit__z"MatplotlibBackendMananger.__exit__$  s.    	NN4112 		s   " 	..N)r5   r`   ra   r}  r  rE   rF   r>   rv  rv    s    rF   rv  c           	        t               5  dd lm} d}d}|j                  dd       |j	                  d      }|j                  ddd	|  d	|
       t               }|j                  ||dddd       |j                  |       |j                  d       |j                         j                  d      }|j                  d      }||d  }	t        j                  dd|	t        j                        }	t        j                  dd|	      }	t        j                   d|	      }
|
r:t#        |
j%                  d            }||z  }t        j                  dd| d|	      }	d|  d}d d d         	 S # 1 sw Y   xY w)Nr      i,  mathtextcm)fontset){Gz?r  )figsize$)fontsizeTsvgtightg        )dpitransparentformatbbox_inches
pad_inchesr0   z<svg z<metadata>.*<\/metadata>r2   )flagsz width="[^"]+"zheight="([\d.]+)pt"rx   zheight="[\d.]+pt"zheight="zem"z<span style='font-size: 0px'>z</span>)rv  matplotlib.pyplotpyplotrcfigurerA  r   savefigcloseseekr   r6   indexresubDOTALLsearchr  group)formula_argspltr  r  figoutputxml_code	svg_startsvg_codeheight_matchheight
new_height	copy_codes                 r>   tex2svgr  -  s|   	"	$ E'z4(jjj.A!G9A: 	 	
 			#A;;=''0NN7+	IJ'665r8299U66+R:yy!7B<--a01F(*Jvv$C&@(H 4G9GD	?E@ [
##AE Es   EE00E9c                d    t        t        j                  j                  t	        |                   S rJ   )r   r   r   abspathr   )r   s    r>   r  r  Q  s    D	*++rF   c                    t        |       j                         t        |      j                         }} 	 | j                  |       y# t        $ r Y yw xY w)z
    True if path_1 is a descendant (i.e. located within) path_2 or if the paths are the
    same, returns False otherwise.
    Parameters:
        path_1: str or Path (to file or directory)
        path_2: str or Path (to file or directory)
    TF)r  r   relative_tor<  )path_1path_2s     r>   is_in_or_equalr  U  sO     V_,,.0G0G0IFF6" s   A 	AAc                    ddl m} t        | t        t        f      rt	        |       g} |j
                  j                  | D cg c]  }t	        |      j                          c}       yc c}w )a  
    Set the static paths to be served by the gradio app.

    Static files are are served directly from the file system instead of being copied. They are served to users with The Content-Disposition HTTP header set to "inline"
    when sending these files to users. This indicates that the file should be displayed directly in the browser window if possible.
    This function is useful when you want to serve files that you know will not be modified during the lifetime of the gradio app (like files used in gr.Examples).
    By setting static paths, your app will launch faster and it will consume less disk space.
    Calling this function will set the static paths for all gradio applications defined in the same interpreter session until it is called again or the session ends.

    Parameters:
        paths: filepath or list of filepaths or directory names to be served by the gradio app. If it is a directory name, ALL files located within that directory will be considered static and not moved to the gradio cache. This also means that ALL files in that directory will be accessible over the network.
    Example:
        import gradio as gr

        # Paths can be a list of strings or pathlib.Path objects
        # corresponding to filenames or directories.
        gr.set_static_paths(paths=["test/test_files/"])

        # The example files and the default value of the input
        # will not be copied to the gradio cache and will be served directly.
        demo = gr.Interface(
            lambda s: s.rotate(45),
            gr.Image(value="test/test_files/cheetah1.jpg", type="pil"),
            gr.Image(),
            examples=["test/test_files/bus.png"],
        )

        demo.launch()
    r   _StaticFilesN)gradio.data_classesr  r   r   r   	all_pathsr  r   )pathsr  ps      r>   set_static_pathsr  e  sM    > 1%#t%e!!e"D47??#4"DE"Ds    A*c                :    ddl m} t        | |j                        S )zBReturns True if the file is a static file (and not moved to cache)r   r  )r  r  _is_static_filer  )r   r  s     r>   is_static_filer    s    09l&<&<==rF   c                     t         t        t        t        f      syt         t              r j                   t         t              rt                 j                         syt         fd|D              S )zZ
    Returns True if the file is a static file (i.e. is is in the static files list).
    Fc              3  6   K   | ]  }t        |        y wrJ   r  )ra  static_filer   s     r>   rc  z"_is_static_file.<locals>.<genexpr>  s     V+~i5V   )r   r   r   r"   r   r"  r  )r   static_filess   ` r>   r  r    s_     i#tX!67)X&NN	)S!O	!VVVVrF   z<[^
>]*(?:
[^
>]*)*>c                @    t        j                  t        d| xs d      S rp  )r  r  HTML_TAG_RE)raw_htmls    r>   remove_html_tagsr    s    66+r8>r22rF   c                     t        j                         } d}| rNt        j                  |       }d|j                  t        j
                  d      vr	 |S | j                  } |dz  }| rN|S )z7
    Find the first stack frame not inside Gradio.
    r   z/gradio//rx   )rU  currentframegetfiler  r   sepf_back)framenfnames      r>   find_user_stack_levelr    si       "E	A
&U]]266377 H 	Q  HrF   c                  "     e Zd ZdZ fdZ xZS )NamedStringa  
    Subclass of str that includes a .name attribute equal to the value of the string itself. This class is used when returning
    a value from the `.preprocess()` methods of the File and UploadButton components. Before Gradio 4.0, these methods returned a file
    object which was then converted to a string filepath using the `.name` attribute. In Gradio 4.0, these methods now return a str
    filepath directly, but to maintain backwards compatibility, we use this class instead of a regular str.
    c                V    t         |           |rt        |       | _        y d| _        y rp  )rf   rg   r   r  )rQ   r  ro   s     r>   rg   zNamedString.__init__  s!    !%CI	2	rF   )r5   r`   ra   r  rg   r   r   s   @r>   r  r    s    . .rF   r  c               #  *   K   d} 	 d|   | dz  } w)z
    A generator that provides default input labels for components when the user's function
    does not have named parameters. The labels are of the form "input 0", "input 1", etc.
    r   zinput rx   rE   )r  s    r>   default_input_labelsr    s*     
 	
A
qcl	Q s   c                    t         j                  j                  |       }t        j                  j                  t        j                  j                  |j                              d   }|r|dd S dS )a  
    Returns the file extension (without the dot) from a file path or URL. If the file path or URL does not have a file extension, returns an empty string.
    For example, "https://example.com/avatar/xxxx.mp4?se=2023-11-16T06:51:23Z&sp=r" would return "mp4".
    rx   Nr2   )r7  r   r8  r   r   splitextbasename)file_path_or_url
parsed_urlfile_extensions      r>   #get_extension_from_file_path_or_urlr    sY    
 &&'78JWW%%bgg&6&6z&GHKN!/>!"7R7rF   KVc                  :     e Zd Zdd fdZd fdZd fdZ xZS )LRUCachec                0    t         |           || _        y rJ   )rf   rg   max_size)rQ   r  ro   s     r>   rg   zLRUCache.__init__  s    %rF   c                    || v r| j                  |       n*t        |       | j                  k\  r| j                  d       t        |   ||       y )NF)last)move_to_endr   r  popitemrf   __setitem__)rQ   r	  r   ro   s      r>   r  zLRUCache.__setitem__  sE    $;S!Y$--'LLeL$C'rF   c                "    t         |   |      S rJ   )rf   __getitem__)rQ   r	  ro   s     r>   r  zLRUCache.__getitem__  s    w"3''rF   )d   )r  r   )r	  r  r   r  r^   r   )r	  r  r^   r  )r5   r`   ra   rg   r  r  r   r   s   @r>   r  r    s    &(( (rF   r  c                 T    t        t        j                  j                  dd            S )NGRADIO_EXAMPLES_CACHEz.gradio/cached_examples)r   r   r!  r:   rE   rF   r>   get_cache_folderr    s    

68QRSSrF   c                "    dfd	 | |      S )Nc           	        |g }g }| |k(  r|S t        |       t        |      ur|j                  d||g       |S t        | t              r3|j	                  |       r"|j                  d||t        |       d  g       |S t        | t              rt        t        |       t        |            }t        |      D ]%  }|j                   	| |   ||   ||gz                ' t        |t        |             D ]  }|j                  d||gz   d g        t        |t        |            D ]  }|j                  d||gz   ||   g        d}|D ]  }|d   dk(  s|d   d   |z
  g|d<   |dz  }! |S t        | t              rp| D ]B  }||v r$|j                   	| |   ||   ||gz                +|j                  d||gz   d g       D |D ]"  }|| vs|j                  d||gz   ||   g       $ |S |j                  d||g       |S )Nr  r  deleteaddr   rx   r]  )r  r  r   r   r  r   r   minranger  rg  )
obj1obj2r   editscommon_lengthr  deletes_seeneditr	  compare_objectss
            r>   r  zdiff.<locals>.compare_objects  s?   <D4<L:T$Z'LL)T401LdC T__T%:LL(D$s4y{*;<=LdD!D	3t95M=) L_T!Wd1gtqczJKL=#d)4 ;hs
D9:;=#d)4 ;eTQCZa9:; L &7h&#Awr{\9:DG A%L& LdD! A$;LLcDItse|!TULL(DC5L$!?@	A
  Cd?LL%tCy!ABC Lit,-rF   rJ   rE   )oldnewr  s     @r>   diffr    s    -^ 3$$rF   c                     t         j                  j                  d      xs7 t        t	        t        j                               dz  j                               S )NGRADIO_TEMP_DIRr  )r   r!  r:   r   r   tempfile
gettempdirr   rE   rF   r>   get_upload_folderr  $  sC    ::>>+, 	h!!#	$x	/88:1 rF   c           
     n   g }	 t        j                  |       }t	        |       }|j
                  j                         D ]  \  }}|j                  t         j                  j                  t         j                  j                  fv r |S t        ||      rV|j                  t         j                  j                  u r&|j                  |dd|j                  |d      f       |j                  |d|j                  |j                  |d      f        |S # t        $ r t        j                         }Y w xY w)a  
    Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).
    Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.
    FNT)rU  rV  r<  	SignaturerM  rW  r   r^  rZ  ra  VAR_KEYWORDr[  rY  r[  r  r:   )r\  params_inforV  
type_hintsr  	parameters         r>   get_function_paramsr  *  s%   
 K(%%d+	  %J$//557 i>>,,))
 
   &dJ7 1 1 7 77eT:>>$3MNOtY..
tT0JK #  (%%'	(s   D D43D4c                    t        j                  |       j                  }|t         j                  j                  d t
        hv rg S t        |      t        u rt        t        |            S |gS rJ   )
rU  rV  return_annotationr  r[  r   r   rh  r   r   )r\  return_hints     r>   get_return_typesr  F  s]    ##D);;Kw((..h??	+%'H[)**=rF   c                    	 t        j                  |       }t        j                  |d t        j
                        }t        |t              r|S t        j                  |      S # t         j                  $ r | cY S w xY w)z
    If a FileData dictionary has been dumped as part of a string, this function will replace the dict with just the str filepath
    c                    | d   S )Nr   rE   xs    r>   rq  z+simplify_file_data_in_str.<locals>.<lambda>[  s
    1V9 rF   )	r8   r9   JSONDecodeErrorclient_utilstraverseis_file_obj_with_metar   r   r   )r   payloads     r>   simplify_file_data_in_strr  R  sp    **Q- ##$l&H&HG '3::g  s   A$ $A<;A<c                      fd}|S )Nc               ?  "   K    | i | y wrJ   rE   r  r  r(  s     r>   wrappedz%sync_fn_to_generator.<locals>.wrappedc  s     $!&!!s   rE   r(  r  s   ` r>   sync_fn_to_generatorr!  b  s    " NrF   c                      fd}|S )Nc                8   K    | i | d {    y 7 wrJ   rE   r  s     r>   r  z&async_fn_to_generator.<locals>.wrappedj  s     '''''s   	rE   r   s   ` r>   async_fn_to_generatorr$  i  s    ( NrF   c                .     t                fd       }|S )zTurn a function into an async function.
    Useful for internal event handlers defined as lambda functions used in the codebase
    c                    K    | i |S wrJ   rE   )r  r  r  s     r>   r  z&async_lambda.<locals>.function_wrapperu  s     $!&!!s   	r   )r  r  s   ` r>   async_lambdar'  p  s#    
 1X" " rF   c                  8    e Zd ZdZdez  Zdez  Zdez  Zdez  Zy)FileSizerx   i   N)r5   r`   ra   BKBMBGBTBrE   rF   r>   r)  r)  |  s+    	A	B	B	B	BrF   r)  c                &   t        | t              s| | S | j                  dd      } t        d t	        |       D        t        |             }t        | d |       | |d  j                         }}t        t        |d       }|st        d|       ||z  S )N r2   c              3  H   K   | ]  \  }}|j                         r|  y wrJ   )isdigit)ra  r  ro  s      r>   rc  z#_parse_file_size.<locals>.<genexpr>  s     :tq!aiik:s   ""zInvalid file size unit: )
r   r   r  r  r  r   upperr   r)  r<  )sizelast_digit_indexsize_intunitmultiples        r>   _parse_file_sizer9    s    $<<R D:y:CI //0148H8I3J3P3P3RdHxt,H3D6:;;hrF   c                   ddl m t        fd|D              }d}d}d| vrt        d      | d   D ]J  }|d   D ]@  }t	        |t
        t        f      st        |      dk(  s)|d	   d
k(  }|r =|d	   dk(  }|s@ J L |xs |xs |S )zH
    Determines whether a heartbeat is required for a given config.
    r   )Statec              3  6   K   | ]  }t        |        y wrJ   )r   )ra  r  r;  s     r>   rc  z$connect_heartbeat.<locals>.<genexpr>  s     AJue,Ar  Fr  zPDependencies not found in config. Cannot determine whetherheartbeat is required.r     rx   unloadstream)r  r;  r  r<  r   r   rh  r   )r   rT   	any_state
any_unload
any_streamrB  targetr;  s          @r>   connect_heartbeatrD    s     (A&AAIJJV#%
 	

 n% )n 	F&4-0S[A5E#AY(2
#AY(2
	 0
0j0rF   c           
        t        j                         }t        | t        t        t
        t        f      r| }nt        | t              rDt        t        | j                         d       D cg c]  \  }}|t        |      f c}}      }nt        | t        t        f      rt        d | D              }nt        | t              r"t        d t        | t              D              }nWt        | t              r$t        t        |             j!                  d      }n#t        t#        |             j!                  d      }|j%                  t'        |      j!                  d             |j)                         S c c}}w )z2Compute a hash for a deeply nested data structure.c                    t        | d         S r  )hashr  s    r>   rq  zdeep_hash.<locals>.<lambda>  s    d1Q4j rF   )r	  c              3  2   K   | ]  }t        |        y wrJ   	deep_hashra  r  s     r>   rc  zdeep_hash.<locals>.<genexpr>  s     0qil0rd  c              3  2   K   | ]  }t        |        y wrJ   rI  rK  s     r>   rc  zdeep_hash.<locals>.<genexpr>  s     BqilBrd  r0   )hashlibsha256r   r   r  r   r   rg  rh  sortedr   rJ  r   ru   rG  r   encoder   r  repr	hexdigest)ri  hasherr   kr   s        r>   rJ  rJ    s   ^^F#UC/0	C	 #399;4HIAq IaL!
 
C$	'0C00	C	BF3D,ABB	C	"DI%%g.BsG##G,
MM$u+$$W-.s   -E8
c                    dd i}|xs t        | t              }|r\t        | t              r>| j                  |d<   | j                  |d<   | j                  |d<   | j
                  |d<   |S t        |       |d<   |S )Nr   durationvisibletitle)r   r   messagerV  rW  rX  r   )r   
show_errorcontents      r>   error_payloadr\    s     6=dOG:z%:JeX&$}}GG"'..GJ!&GI${{GG N  #5zGGNrF   c                  :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
UnhashableKeyDictz
    Essentially a list of key-value tuples that allows for keys that are not hashable,
    but acts like a dictionary for convenience.
    c                    g | _         y rJ   datarP   s    r>   rg   zUnhashableKeyDict.__init__  s	    	rF   c                `    | j                   D ]  \  }}t        ||      s|c S  t        |      rJ   )ra  r  KeyError)rQ   r	  rT  r   s       r>   r  zUnhashableKeyDict.__getitem__  s4    II 	DAq!S!	 smrF   c                    t        | j                        D ]'  \  }\  }}t        ||      s||f| j                  |<    y  | j                  j                  ||f       y rJ   )r  ra  r  r  )rQ   r	  r   r  rT  r  s         r>   r  zUnhashableKeyDict.__setitem__  sX    "499- 	IAv1!S! #U|		!	 			#u&rF   c                    t        | j                        D ]#  \  }\  }}t        ||      s| j                  |=  y  t        |      rJ   )r  ra  r  rc  )rQ   r	  r  rT  r  s        r>   __delitem__zUnhashableKeyDict.__delitem__  sF    "499- 	IAv1!S!IIaL	 smrF   c                (    d | j                   D        S )Nc              3  &   K   | ]	  \  }}|  y wrJ   rE   )ra  rT  r  s      r>   rc  z-UnhashableKeyDict.__iter__.<locals>.<genexpr>  s     (da(s   r`  rP   s    r>   __iter__zUnhashableKeyDict.__iter__  s    (dii((rF   c                ,    t        | j                        S rJ   )r   ra  rP   s    r>   __len__zUnhashableKeyDict.__len__  s    499~rF   c                L    | j                   D cg c]  \  }}|	 c}}S c c}}w rJ   r`  )rQ   r  r   s      r>   as_listzUnhashableKeyDict.as_list  s    "ii(da(((s    N)r5   r`   ra   r  rg   r  r  rf  ri  rk  rm  rE   rF   r>   r^  r^    s*    
'))rF   r^  c                   t         j                  j                  t         j                  j                  fD cg c]  }||dk7  s| }}t	        j
                  |      t         j                  j                  |       }t        fd|D              s5t         j                  j                        sdk(  sj                  d      r
t               |S c c}w )ztSafely path to a base directory to avoid escaping the base directory.
    Borrowed from: werkzeug.security.safe_joinr  c              3  &   K   | ]  }|v  
 y wrJ   rE   )ra  r  r   s     r>   rc  zsafe_join.<locals>.<genexpr>	  s     4C8O4r  z..z../)r   r   r  altsep	posixpathnormpathjoinr  isabsr  r%   )	directoryr   r  _os_alt_sepsfullpathr   s        @r>   	safe_joinrx    s     RWW^^4CSVJL  !!$'Hww||Ix0H4|4477=="tu%  Os   C CCc                     t         fd|D              }|ryt         fd|D              ryt         fd|D              ryy)Nc              3     K   | ]>  }t        t              j                         t        |      j                                @ y wrJ   )r  r   r  )ra  blocked_pathr   s     r>   rc  z"is_allowed_file.<locals>.<genexpr>  s9       	s4y(#l*;*A*A*CDs   AA)Fin_blocklistc              3  6   K   | ]  }t        |        y wrJ   r  )ra  allowed_pathr   s     r>   rc  z"is_allowed_file.<locals>.<genexpr>!       
P,>$-
Pr  )Tallowedc              3  6   K   | ]  }t        |        y wrJ   r  )ra  created_pathr   s     r>   rc  z"is_allowed_file.<locals>.<genexpr>#  r  r  )Tcreated)Fnot_created_or_allowed)r  )r   blocked_pathsallowed_pathscreated_pathsr|  s   `    r>   is_allowed_filer    sI      ) L $

P-
PP

P-
PP*rF   c                 Z   t         j                  j                  d      } | r| S t        j                  d      }|r|S 	 t
        j                  dk(  rft        j                  ddg      j                         j                         j                  d      d   }t         j                  j                  |      r|S 	 t
        j                  dk7  r3t        j                  ddg      j                         j                         S 	 t
        j                   dd	d
dg}|D ]%  }t         j                  j                  |      s#|c S  t         j                  j                  dd      }|j                  t         j"                        }|D ]Z  }t         j                  j%                  |t
        j                  dk(  rdnd      }t         j                  j                  |      sX|c S  t'        d       t'        d       y # t        j                  $ r Y Rw xY w# t        j                  t        f$ r Y *w xY w)NGRADIO_NODE_PATHr   win32wherez
r   whichz/usr/bin/nodez/usr/local/bin/nodez C:\Program Files\nodejs\node.exez&C:\Program Files (x86)\nodejs\node.exePATHr2   znode.exez;Unable to find node install path, falling back to SPA mode.zIf you wish to use the node backend, please install node 20 and/ or set the path with the GRADIO_NODE_PATH environment variable.)r   r!  r:   shutilr  r   platform
subprocesscheck_outputr6   r7   r   r   r"  CalledProcessErrorFileNotFoundError
executablepathseprs  r   )	env_node_pathwhich_node_pathwindows_pathcommon_paths	node_pathenv_path	path_dirsru  	full_paths	            r>   get_node_pathr  (  s   JJNN#56Mll6*O<<7"''&(9:vq"  ww~~l+##
<<7"**GV+<=DDFLLNN # 	-3L " 	77>>)$
 zz~~fb)Hrzz*I 	GGLLS\\W%<z&
	 77>>)$ 

GH	 	K Q ((  ))+<= s%   A8G3 8AH 3H
	H
H*)H*c                R    | g S t        | t        t        f      rt        |       S | gS rJ   )r   r   rh  r   s    r>   none_or_singleton_to_listr  g  s+    }	%$'E{7NrF   c           	        t        t        j                  j                  d      j	                  t        t        d      | z                    }t        |      j                         rt        |       |S t        d|        )a)  Get the path to an icon file in the "gradio/icons/" directory
    and return it as a static file path so that it can be used by components.

    Parameters:
        icon_name: Name of the icon file (e.g. "plus.svg")
    Returns:
        str: Full path to the icon file served as a static file
    r  iconszIcon file not found: )	r   r   	resourcesfilesjoinpathr   r"  r  r<  )	icon_name	icon_paths     r>   get_icon_pathr  o  sn     !!(+44Sg9R5STI I#
,YK8
99rF   c                h    i }| D ]*  \  }}t        |d      r|j                         ||<   &|||<   , |S )zb
    A utility function to convert a dataclass that includes pydantic fields to a dictionary.
    
model_dump)hasattrr  )r   rA  r	  r   s       r>   dict_factoryr    sH     	A 
U5,'%%'AcFAcF	
 HrF   c                   | j                   }d}i }|s||fS |j                         j                  d      }g }|D ]9  }|j                         }|j                  d      r n|s)|j	                  |       ; dj                  |      }	 t        d t        |      D        t        |            }||dz   d D ]f  }|j                         }|s	 d|v rL|j                  dd      \  }}	|j                  d      d	   j                         }|r|	j                         ||<   h 	 ||fS # t        $ r Y yw xY w# t        $ r Y ||fS w xY w)
a  
    Get the description of a function and its parameters by parsing the docstring.
    The docstring should be formatted as follows: first lines are the description
    of the function, then a line starts with "Args:", "Parameters:", or "Arguments:",
    followed by lines of the form "param_name: description".

    Parameters:
        fn: The function to get the docstring for.

    Returns:
        - The docstring of the function
        - A dictionary of parameter names and their descriptions
    r2   r  zArgs:zParameters:z
Arguments:r0  c              3  d   K   | ](  \  }}|j                         j                  d       r| * yw)r  N)r7   r  )ra  r  lines      r>   rc  z+get_function_description.<locals>.<genexpr>  s1      At::<**+QR s   .0rx   N:r   )
r  r7   r   r  r  rs  r  r  r   r;   )
r(  fn_docstringdescriptionrW  linesdescription_linesr  param_start_idx
param_name
param_descs
             r>   get_function_descriptionr    s~    ::LKJJ&& &&t,E +zz|??AB$$T*+ ((,-K(/
 J
 /A-/0 	D::<D$;-1ZZQ-?*J
!+!1!1#!6q!9!?!?!AJ!1;1A1A1C
:.	" 
""    
""s8   AD2 AD#D2 #	D/,D2 .D//D2 2	E E)r^   r   )r^   zasyncio.Lock)r^   zasyncio.Event)r   r   )r   r   r^   zModuleType | None)r   rd   )r   r   r  r   r^   r   )r   r'   r  r'   r   )r^   
str | None)rE  r   r^   r   )r\  r   r^   	list[Any])ri  r   r^   r   ))r   )rz  r    r{  r    r  rh  )FN)r  rg  r  r   r  zlist[str] | Noner^   rg  )r  zlist[Any] | Anyr^   r   )r^   z*list[type[Component] | type[BlockContext]])r  r   r^   z$type[Component] | type[BlockContext])r\  r   )r   z
Path | str)r   str | floatr^   r  )rX  r  r^   r  )r  r   r  r   )r  r   r^   r   )NNNN)
r  r   r  Callable | Noner  Iterable | Noner  r  r  r  )r(  r   rT   r'   r#  r  r"  r   r$  zRequest | Noner&  zSessionState | None)r1  zset[str]r^   r   )r:  r   r;  r   r#  r   r<  r   )r  zlist[dict[str, Any]]r^   z	list[int])r(  r   r  r   re  r   )r   
str | Pathr^   r   )r  r  r  r  r^   r   )r  zstr | Path | list[str | Path]r^   r   )r   r   )r   r   r  z
list[Path]r^   r   )r  r  r^   r   )r^   r   )r  r   r^   r   )r^   r   )r\  r   r^   z list[tuple[str, bool, Any, Any]])r\  r   r^   r   )r  r   r^   r   )r4  zstr | int | Noner^   z
int | None)r   r    r^   r   )r   zBaseException | NonerZ  r   r^   z$dict[str, bool | str | float | None])ru  r!   r   r#   r^   r   )
r   r   r  Sequence[str | Path]r  r  r  r  r^   zTtuple[bool, Literal['in_blocklist', 'allowed', 'created', 'not_created_or_allowed']])r   r   r^   r   )r  r   r^   r   )r(  r   r^   ztuple[str, dict[str, str]])r  
__future__r   r   rA   re  r  rM  r   importlib.resourcesimportlib.utilrU  r8   json.decoderr   r3   rq  r  r  r  r   r  	threadingr   r   rL  urllib.parser7  rM  rc  abcr   r   collectionsr   collections.abcr   r   r	   r
   r   r   
contextlibr   r   ior   pathlibr   typesr   r   r   r   r   r   r   r   r   r   r  gradio_client.utilsutilsr  r=  r   gradio_client.documentationr   gradio_client.exceptionsr   typing_extensionsr   r  r   r   r  r    r!   r"   r#   gradio.exceptionsr$   r%   r  r&   r'   r  r)   rT  r*   r+   gradio.state_holderr,   r-   r.   r?   rG   rL   rN   rd   r   r   r   r   r   r   r  r~   r  r#  r&  r-  r1  rI  r   rs  dirnamer   rL  rS  r]  r`  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r)  r7  r=  rF  rM  r[  rl  rh  rn  rv  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)  r9  rD  rJ  r\  r^  rx  r  r  r  r  r  r  rE   rF   r>   <module>r     sr    " 
           	   	   
         # #  &    &	 	 	  *   0 - '  -  62+*0cNCL	
'3 '$($ ($V!S ! 4 	!HcL.&2R" 2* bggoofoo>P "& NWHH(8HEJHX KO!7G	"8:98-
 
 !      I "&#' $"&III !I 	I
  IX  	
  B J
&%7(%
P5  &!$H,  
"F "FJ>W bjj2BII>3
.# 
.8 CLCL({GAqDM ( T0%f8	 	  180-1) $) $)N(+
+'+ (+ (	+
+*<~:$
<#rF   