
    Fg                    T   S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	rSSK
rSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJrJ r   SSK!J"r"  SSK#J$r$J%r%J&r&J'r'J(r(J)r)  SSK*J+r+  SSKJ,r,  SS	K-J.r.  SS
K/J0r0  SSK1J2r2J3r3  SSKJ4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;  SSK<r<SSK=J>r?  SSK@r@SSKArASSKBJCrC  SSKDJErE  SSKFrFSSKGJHrH  SSKIJJrJJKrKJLrLJMrM  SSKNJOrOJPrP  \4(       a  SSKQJRrRJSrS  SSKTJUrU  SSKVJWrWJXrX  SSKYJZrZ  \E" S5      r[\9" S5      r\SxS jr]SyS jr^SzS jr_ " S S\5      r` " S S\`5      ra " S S \b5      rc\c" S!5      rdS{S" jreS|S# jrfS}S$ jrgS~S% jrhSS& jriSS' jrjSS( jrkSS) jrlSS* jrmSS+ jrnSS, jroSS- jrp\R                  R                  \R                  R                  \FR                  5      S.5      ruSxS/ jrvSS0 jrwSS1 jrx S     SS2 jjrySSS3 jjrzSS4 jr{SS5 jr|S6 r}SS7 jr~SS8 jrS9 r " S: S;5      rS< r\+SS= j5       r\+S> 5       rSS? jrSS@ jrSSA jrSSB jrSC r    S         SSD jjr            SSE jrSSF jrSSG jr    SSH jrSI rSJ rSSK jr " SL SM\5      r " SN SO5      rSP rSSQ jrSSR jr\C" 5       SSS j5       rSST jrSSU jr\GR6                  " SV\GR8                  5      rSSW jrSSX jr " SY SZ\5      rS[ rSS\ jr\9" S]5      r\9" S^5      r " S_ S`\"\6\\4   5      rSSa jrSb rSxSc jrSSd jrSSe jrSf rSg rSh rSSi jr " Sj Sk5      rSSl jrSSm jrSn r      SSo jr " Sp Sq\(5      rSSr jr          SSs jrSt rSSu jrSSv jrSw rg)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)	ParamSpec)get_blocks_context)BlocksConfigDictDeveloperPathFileDataUserProvidedPath)ErrorInvalidPathError)BlockContextBlocks	Component)AppRequest)SessionStatePTc                      [         R                  " [        S5      R                  S5      R	                  5       n [
        R                  " U 5      nUR                  SS5      nU$ ! [         a     gf = f)Nzpackage.jsonutf-8version )	pkgutilget_data__name__decodestripjsonloadsget	Exception)package_json_datapackage_datar0   s      ]/Users/admin/workspace/ai/PDFMathTranslate/myenv/lib/python3.13/site-packages/gradio/utils.pyget_package_versionr>   T   sj    X~6==gFLLN 	 zz"34""9b1 s   A!A$ $
A10A1c                 x     [         R                  " 5         [         R                  " 5       $ ! [         a     gf = f)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_lockrF   `   s1     ||~    ), 
99c                 x     [         R                  " 5         [         R                  " 5       $ ! [         a     g f = fN)r@   rA   EventrC   rD   rE   r=   safe_get_stop_eventrK   m   s1     }} rG   c                  <    \ rS rSr\\SS j5       5       rSS jrSrg)BaseReloaderu   c                    g rI   rD   selfs    r=   running_appBaseReloader.running_appv   s     	rE   c                X   U R                   R                  (       d   eU R                   R                  R                  Ul        SUl        U R                   R                  R                  Ul        SUl        U R                   R                  R                  U5        XR                   l        g )NT)rR   blocks_queuehas_launchedmax_file_size
is_runningstate_holderreset)rQ   demos     r=   swap_blocksBaseReloader.swap_blocks{   s    &&&& &&--44 !--44BB%%++D1"&rE   rD   Nreturnr)   r\   r&   )	r4   
__module____qualname____firstlineno__propertyr   rR   r]   __static_attributes__rD   rE   r=   rM   rM   u   s!      	'rE   rM   c                     ^  \ rS rSr S	               S
U 4S jjjr\SS j5       rSS jrSS jrSSS jjr	SU 4S jjr
SrU =r$ )SourceFileReloader   c                   > [         TU ]  5         Xl        X l        X0l        X`l        Xpl        [        U5      U l        XPl	        g rI   )
super__init__app
watch_dirswatch_module_name
stop_event	demo_namer   	demo_filewatch_module)	rQ   rm   rn   ro   rr   rs   rp   rq   	__class__s	           r=   rl   SourceFileReloader.__init__   s;     	$!2$"i(rE   c                    U R                   $ rI   )rm   rP   s    r=   rR   SourceFileReloader.running_app   s    xxrE   c                @    U R                   R                  5       (       + $ rI   )rp   is_setrP   s    r=   should_watchSourceFileReloader.should_watch   s    ??))+++rE   c                8    U R                   R                  5         g rI   )rp   setrP   s    r=   stopSourceFileReloader.stop   s    rE   c                b    XR                   l        U R                   =R                  S-  sl        g )N   )rm   change_typechange_count)rQ   r   s     r=   alert_changeSourceFileReloader.alert_change   s!    *"rE   c                   > U R                   R                  n[        TU ]  U5        U(       a  [	        X!5        UR                  5       Ul        U R                  S5        g )Nreload)rR   rU   rk   r]   reassign_keysget_config_fileconfigr   )rQ   r\   
old_blocksrt   s      r=   r]   SourceFileReloader.swap_blocks   sJ    %%,,
D!*+**,(#rE   )rm   rr   rq   rp   rn   rs   ro   )r\   )rm   r)   rn   	list[str]ro   strrr   r   rs   r   rp   zthreading.Eventrq   r   r`   Noner_   r`   boolr`   r   )r   )r   zLiteral['reload', 'error']ra   )r4   rb   rc   rd   rl   re   rR   rz   r~   r   r]   rf   __classcell__rt   s   @r=   rh   rh      s      )) ) 	)
 ) !) $) ) 
) )&  ,#$ $rE   rh   c                  .    \ rS rSrSS jrS rSS jrSrg)DynamicBoolean   c                $    [        U5      U l        g rI   r   valuerQ   r   s     r=   rl   DynamicBoolean.__init__       %[
rE   c                    U R                   $ rI   r   rP   s    r=   __bool__DynamicBoolean.__bool__   s    zzrE   c                $    [        U5      U l        g rI   r   r   s     r=   r}   DynamicBoolean.set   r   rE   r   N)r   int)r4   rb   rc   rd   rl   r   r}   rf   rD   rE   r=   r   r      s    !!rE   r   Tc                   [        U SS9 nUR                  5       nSSS5        [        R                  " W5      nSS jn[        R                  " U5       Hb  nU" U5      (       d  M  [        U[        R                  5      (       d   e[        R                  " UR                  UR                  S9/Ul
        Md     [        X0SS9nU$ ! , (       d  f       N= f)	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.
r/   )encodingNc                   [        U [        R                  5      =(       GaJ    [        U R                  [        R                  5      =(       Ga    [        U R                  R
                  [        R                  5      =(       a    U R                  R
                  R                  S:H  =(       a    [        U R                  R                  5      S:H  =(       a    [        U R                  R                  S   [        R                  5      =(       a^    [        U R                  R                  S   [        R                  5      =(       a&    U R                  R                  S   R                  S:H  $ )z*Find the if __name__ == '__main__': block.r4   r   r   __main__)
isinstanceastIftestCompareleftNameidlenopsEqcomparatorsConstants)exprs    r=   _is_if_name_main8_remove_if_name_main_codeblock.<locals>._is_if_name_main   s     tSVV$ 9 9499ckk29 9499>>38849 		!!Z/9 DIIMM"a'	9
 499==+SVV49 499003S\\B9 		%%a(**j8		
rE   )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
 D!!dCFF++++QRDI  4&AL5 
+	*s   C
Cc                    [         R                  R                  5        H+  u  pUS;  d  M  [        USS 5      [	        U 5      :X  d  M)  Us  $    g )N>   r   __mp_main____file__)sysmodulesitemsgetattrr   )source_filer   vs      r=   _find_moduler      sL    !!#//GAz44PTWU
 5
 H	 $
 rE   c                  ^^^ [         R                  S5        SSKJn  SUl        SUU4S jjnSU4S jjmU R
                   Vs/ s H  n[        U5      PM     snmSSKnT H(  nUR                  R                  S[        U5      5        M*     0 mU R                  n[        [        U R                  5      5      n[        XeR                  5        XTR                   U R"                  '   U R%                  5       (       GaH  U" 5       nU(       Ga
  ['        SU 35         UR(                  S	:X  a  [        [        U5      5      nXpR                  :w  am  [+        U5      n	U	(       a[  [        XR                  5        UR                   U	R,                  R/                  S
5      S      n
X:w  a  [0        R2                  " U
5        [        [        U R                  5      5      n[        XR                  5        [I        XPRJ                  5      nU RM                  U5        0 m[N        RP                  " S5        U R%                  5       (       a  GMG  ggs  snf ! [4         a  n['        SU R"                   S35        [7        U[8        5      (       a  UR:                  (       a  [<        R>                  " 5         0 mU RA                  S5        [<        RB                  " 5       U RD                  l#         SnAGM   SnAff = f)zaWatch python files in a given module.

get_changes is taken from uvicorn's default file watcher.
Fr   )reload_threadTc                    > T" 5        HB  n  U R                  5       R                  nTR                  U 5      nUc  UTU '   M9  X:  d  M@  U s  $    g ! [         a     MT  f = frI   )statst_mtimeOSErrorr9   )r   mtimeold_timeiter_py_filesmtimess      r=   get_changeswatchfn.<locals>.get_changes   sk    !OD		,, zz$'H$t! $   s   A
AAc               3     >#    T Hi  n [        U R                  S5      5       H  nUR                  5       v   M     [        U R                  S5      5       H  nUR                  5       v   M     Mk     g 7f)Nz*.pyz*.css)listrglobresolve)
reload_dirpathreload_dirss     r=   r   watchfn.<locals>.iter_py_files  s\     %JZ--f56lln$ 7Z--g67lln$ 8 &s   A1A4NzChanges detected in: z.py.z
Reloading z& failed with the following exception: errorg?)r`   zPath | None)r`   zIterator[Path]))	NO_RELOADr}   gradio.cli.commands.reloadr   running_reloadrn   r   r   r   insertr   rs   r   rr   r   __dict__r   ro   rz   printsuffixr   r4   split	importlibr   r:   r   r#   print_exception	traceback	print_excr   
format_excrm   reload_error_messager   rq   r]   timesleep)reloaderr   r   dir_r   moduleno_reload_source_codechangedchanged_in_copychanged_moduletop_level_parentchanged_demo_filer   r\   r   r   r   s                 @@@r=   watchfnr     sX    MM%
 9#'M  % +3*=*=>*=$4:*=>K3t9%  F ""F:3x?Q?Q;RS	0.4KK**+



!
!-)'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 6#5#56D  &F

4W 


!
! ?X  	 !;!; <<bc "%//53H3H'')%%g.4=4H4H4J1	s    ICI 
K-BK((K-c                |    SS jn U" U 5      U" U5      :H  $ ! [          a     X:H  s $ ! [         a      gf = ff = f)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                j    [         R                  " U [         R                  [         R                  -  S9$ )N)option)orjsondumpsOPT_SERIALIZE_NUMPYOPT_PASSTHROUGH_DATETIME)as    r=   
_serializedeep_equal.<locals>._serializeV  s*    ||--0O0OO
 	
rE   F)r  r   r`   bytes)	TypeErrorr:   )r  br  s      r=   
deep_equalr  N  sL    
!}
1-- 	6M 		s     
;);
7;7;c                   ^^^ SSK Jm  UR                   Vs/ s H  o"R                  c  M  UR                  PM     snm    SUUU4S jjmT" X5        g s  snf )Nr   )r%   c           	     ^  > [        UR                  5       GH  u  p#U (       a)  U[        U R                  5      :  a  U R                  U   nOS nUR                  c{  UR                  UR                  :X  aL  UbI  UR                  T;  a9  [        [        USS 5      [        USS 5      5      (       a  UR                  Ul        OSUR                   S3Ul        [        UT5      (       d  M  [        UT5      (       a%  UR                  UR                  :X  a  T" XC5        GM	  T" S U5        GM     g )Nr   __)		enumeratechildrenr   keyrt   r  r   _idr   )old_contextnew_contexti	new_block	old_blockr%   assigned_keysreassign_context_keyss        r=   r"  ,reassign_keys.<locals>.reassign_context_keysl  s     &k&:&:;LAq3{';';#<<'003	 	}}$''9+>+>>!-!]:"	7D9	7D9 
 %.MMIM&(r$:IM)\22y,77!++y/B/BB))?)$	:5 <rE   )r  zBlockContext | Noner  r%   )gradio.blocksr%   r  r  )r   
new_blocksblockr%   r!  r"  s      @@@r=   r   r   e  s\    *  *222eii			2M;(;7C; ;> *1Gs
   AAc                 v    Sn  SSK Jn  U" 5       nS[        U5      ;   a  Sn U $ ! [        [        4 a     U $ f = f)zZ
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   $ 88c                     [        [        R                  R                  S5      =(       d    [        R                  R                  S5      5      $ )NKAGGLE_KERNEL_RUN_TYPEGFOOTBALL_DATA_DIR)r   osenvironr9   rD   rE   r=   kaggle_checkr5    s3    


/0XBJJNNCW4X rE   c                      SS K n U R                  S5      nUR                  5       nSUS   R                  5       ;   $ ! [         a     gf = f)Nr   sts	sagemakerArnF)boto3clientget_caller_identitylowerr:   )r:  r;  responses      r=   sagemaker_checkr?    sP    e$--/huo33555 s   := 
A
	A
c                 Z    Sn  SSK Jn  U" 5       b  Sn U $ ! [        [        4 a     U $ f = f)zc
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_checkrB    sE    
 J7=$J  # s    **c                 d    [         R                  " S5      S:X  a  [         R                  " S5      $ g )NSYSTEMspacesSPACE_IDr3  getenvrD   rE   r=   	get_spacerI    s%    	yyh&yy$$rE   c                 4    [         R                  " S5      S:H  $ )NSPACES_ZERO_GPUtruerG  rD   rE   r=   is_zero_gpu_spacerM    s    99&'611rE   c                    [         R                  R                  U 5      n[        UR                  UR
                  UR                  /5      nU=(       a    UR                  S;   nU(       d  U $  [        R                  " U SS9nUR                  [        R                  R                  :X  a  UR                  n U $ ! [         a    Sn Ncf = f! [        R                  [        R                  [        R                   4 a     U $ f = f)N)httphttpsF   )timeout)urllibr   urlparseallschemenetlocr   
ValueErrorhttpxr9   status_codecodesOKtext
InvalidURLRequestErrorTimeoutException)articleresultis_urlr>  s       r=   download_if_urlrd    s    &&w/fmmV]]FKK@A>FMM->> 99Wa05;;>>1mmG N   e00%2H2HI Ns%   A#B: /A	C :C	C	3DDzhash_seed.txtc                     [         R                  R                  [        5      (       a7  [	        [        5       n U R                  5       R                  5       sS S S 5        $ [	        [        S5       n [        R                  " 5       R                  nU R                  U5        UsS S S 5        $ ! , (       d  f       g = f! , (       d  f       g = f! [         a"    [        R                  " 5       R                  s $ f = f)Nw)r3  r   existsHASH_SEED_PATHr   r   r6   uuiduuid4hexwriter:   )jseeds     r=   get_hash_seedro    s    
 77>>.))n%vvx~~' &% nc*azz|'' +* &% +*   zz| sR   7C B-	C !C 12B>#	C -
B;7C ;C >
CC C )C;:C;c                    [         R                  " U 5      nUR                  R                  5        Vs/ s H8  nUR                  [         R
                  R                  La  UR                  OS PM:     sn$ s  snf rI   )inspect	signature
parametersvaluesdefault	Parameterempty)funcrr  r   s      r=   get_default_argsry    sh    !!$'I %%,,..A YYg&7&7&=&==		4G.  s   ?A5c           	     `    [         R                  " U 5      $ ! [         Ga
    [        U [        5      (       aA  U R                  5        VVs0 s H  u  p[        U5      [        U5      _M     Os  snnf snns $ [        U [        5      (       a$  U  Vs/ s H  n[        U5      PM     Os  snf sns $ [        U [        5      (       a  [        S U  5       5      s $ [        U [        5      (       a$  U  Vs1 s H  n[        U5      iM     Os  snf sns $ [         R                   " U 5      s $ f = f)Nc              3  8   #    U  H  n[        U5      v   M     g 7frI   )safe_deepcopy).0items     r=   	<genexpr> safe_deepcopy.<locals>.<genexpr>  s     =t,,   )
copydeepcopyr:   r   dictr   r|  r   tupler}   )objr  r   r~  s       r=   r|  r|    s    "}}S!! "c4  KN99;KVZSc"M%$88;  T""478CDM$'C88U##====S!!478CDM$'C8899S>!"sK    3D-!A-,D-9D-B('	D-2'D-D-4D
		D-D-,D-c                H  ^ ^^^ [         R                  " T 5      m [         R                  " T5      m[        R                  " [        R                  " T 5      5      m [        R                  " [        R                  " T5      5      mU H  nT U   TU   :w  d  M  [        SU 35      e   [        T S   5      [        TS   5      :w  a  [        S5      eU U4S jmUU4S jmST ;   aC  ST;  a  [        S5      eT S   R                  S/ 5      nTS   R                  S/ 5      nT" XE5        S	T ;   a  S	T;  a  [        S
5      e[        T S	   TS	   SS9 H  u  pg[        UR                  S5      UR                  S5      SS9 H  u  pT" US   U	S   5        M     [        UR                  S5      UR                  S5      SS9 H  u  pT" X5        M     [        UR                  S5      UR                  S5      SS9 H  u  pT" X5        M     Xg:w  d  M  [        U SU 35      e   g)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                  >^ ^ [        [        U 4S jTS   5      5      n[        U5      S:X  a  [        ST  35      eUS   n[        [        U4S jTS   5      5      n[        U5      S:X  a  [        ST 35      eUS   n[        R
                  " U5      nUR                  S5        [        R
                  " U5      nUR                  S5        X#:w  a  [        U SU 35      eg )Nc                   > U S   T:H  $ Nr   rD   )c
config1_ids    r=   <lambda>[assert_configs_are_equivalent_besides_ids.<locals>.assert_same_components.<locals>.<lambda>#      1T7j#8rE   r  r   z!Could not find component with id c                   > U S   T:H  $ r  rD   )r  
config2_ids    r=   r  r  '  r  rE   r    does not match )r   filterr   rX  r  r  pop)r  r  c1c2config1config2s   ``  r=   assert_same_componentsIassert_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 rE   c                   > [        XSS9 H1  u  p#T" US   US   5        SU;   d  SU;   d  M"  T" US   US   5        M3     g )NFstrictr   r  )zip)	children1chidren2child1child2r  same_children_recursives       r=   r  Jassert_configs_are_equivalent_besides_ids.<locals>.same_children_recursive2  sL    !)eDNF"6$<>V#zV';'z(:F:<NO ErE   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outputsr  T)
r  r  r7   r8   r  rX  r   r9   r  r  )r  r  	root_keysr  r  	children2d1d2t1t2i1i2o1o2r  r  s   ``            @@r=   )assert_configs_are_equivalent_besides_idsr  
  s    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		5 (R  N#W^%<U
FB bffY/	1B5Q&r!ube4 RbffX.x0@O&r. PbffY/	1B5Q&r. Rx B4'7t!<==
 rE   c                v    [        U R                  5       5       H  u  p#U(       a  US:X  a  M  Ub  M  X	 M     U $ )z5
Delete keys whose values are None from a dictionary
r   )r   r   )_dict
skip_valuer  r   s       r=   delete_noner  U  s8     5;;=)
#.]
	 *
 LrE   c                .    [        U 5      S:X  a  U S   $ U $ )Nr   r   )r   )_lists    r=   resolve_singletonr  a  s    
5zQQxrE   c                    SS K n U R                  R                  R                  5       U R                  R
                  R                  5       -   n/ nU(       aI  UR                  5       nUR                  UR                  5       5        UR                  U5        U(       a  MI  U Vs/ s H  nUR                  S;  d  M  UPM     sn$ s  snf )Nr   )ChatInterface	Interfacer&   TabbedInterface
NativePlot	SketchBox)
gradior  r(   __subclasses__rU   r%   r  extendappendr4   )grclasses_to_check
subclassessubclassr  s        r=   get_all_componentsr  h  s     	..0
))
 
 
/
/
1	2  J
#'') 7 7 9:(# 
 A::

 	
  s   $C<Cc                     [        5        V s/ s H'  n U R                  R                  S5      (       d  M%  U PM)     sn $ s  sn f )Nzgradio.)r  rb   
startswith)class_s    r=   core_gradio_componentsr    s@     )**F''	2 	*  s   $>>c                   SSK Jn  SSK Jn  [        5        Vs0 s H  o3R                  R                  5       U_M     nnUR                  R                  5        H@  u  pV[        U[        5      (       d  M  [        Xb5      (       d  M.  XdUR                  5       '   MB     U R                  SS5      U;   a  X@R                  SS5         $ [        SU  S35      es  snf )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'   _r1   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.componentsr  r(   r  r4   r=  r   r   r   type
issubclassreplacerX  )cls_namecomponents_moduler(   r  r  nameclss          r=   component_or_layout_classr    s     2+1C1EF1EA**""$a'1EJF&//557	c4  Z%?%?'*tzz|$ 8 R J.**3344

'z 2W 	W  Gs   $Cc                Z    [         R                  " 5       nUR                  U " U0 UD65      $ )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:

)r@   rA   create_task)rx  argskwargs
event_loops       r=   run_coro_in_backgroundr    s-    0 '')J!!$"7"788rE   c                L     [        U 5      $ ! [         a    [        5       Sef = f)z;Helper for yielding StopAsyncIteration from sync iterators.N)nextStopIterationStopAsyncIterationiterators    r=   run_sync_iterator_asyncr    s+    -H~ - ",-s   
 #c                  .    \ rS rSrSrSS jrS rS rSrg)	SyncToAsyncIteratori  z*Treat a synchronous iterator as async one.c                    Xl         X l        g rI   r  limiter)rQ   r  r  s      r=   rl   SyncToAsyncIterator.__init__  s     rE   c                    U $ rI   rD   rP   s    r=   	__aiter__SyncToAsyncIterator.__aiter__  s    rE   c                   #    [         R                  R                  [        U R                  U R
                  S9I S h  vN $  N7f)N)r  )anyio	to_threadrun_syncr  r  r  rP   s    r=   	__anext__SyncToAsyncIterator.__anext__  s:     __--#T]]DLL . 
 
 	
 
s   ;AAAr  Nr   )	r4   rb   rc   rd   __doc__rl   r  r  rf   rD   rE   r=   r  r    s    4
rE   r  c                4   #    [        U 5      I S h  vN $  N7frI   )anextr  s    r=   async_iterationr    s     x   s   c              #     #    [        5       R                  5       n [        R                  " U 5        Sv   [        R                  " U5        g! [        R                  " U5        f = f7f)zBContext manager that sets the working directory to the given path.N)r   absoluter3  chdir)r   origins     r=   set_directoryr    s@      V__F

s   A(A A(A%%A(c               #  6   #     Sv   g! [          a     gf = f7f)z+Context manager that suppresses exceptions.N)r:   rD   rE   r=   no_raise_exceptionr    s      s   	 
c                   ^  [        T [        [        45      (       a  T $ / SQn/ SQn[        U 4S jU 5       5      (       d  [        U 4S jU 5       5      (       a  ST  3m T $ )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  F   >#    U  H  nTR                  U5      v   M     g 7frI   )r  )r}  prefixr   s     r=   r  )sanitize_value_for_csv.<locals>.<genexpr>  s     
B/5F##/s   !c              3  ,   >#    U  H	  oT;   v   M     g 7frI   rD   )r}  sequencer   s     r=   r  r    s      J*:hE*:   ')r   floatr   any)r   unsafe_prefixesunsafe_sequencess   `  r=   sanitize_value_for_csvr    sf    
 %%&&6O=

B/
BBBc J*:J G G E7LrE   c                    / nU  Hb  n[        U[        5      (       a.  U Vs/ s H  n[        U5      PM     nnUR                  U5        MF  [        U5      nUR                  U5        Md     U$ s  snf )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  )rt  sanitized_valuesr   r   sanitized_values        r=   sanitize_list_for_csvr    so    
 eT""BGH%Q5a8%OH##O44U;O##O4   Is   A-c                l    [        U5      nX;  a  U $ SnU  SU 3nXB;   a  US-  nU  SU 3nXB;   a  M  U$ )zSAppends a numerical suffix to `name` so that it does not appear in `list_of_names`.r   r  )r}   )r  list_of_namesset_of_namessuffix_counternew_names        r=   append_unique_suffixr    s]     /LV1^,-&aNq 01H & rE   c                    SS0n [         R                  " XSS9nUR                  S;   a  [         R                  " XSS9R                  $ UR                  $ ! [
         a     gf = f)Nz
User-Agentz8gradio (https://gradio.app/; gradio-team@huggingface.co)T)headersfollow_redirects)i  i  F)rY  headrZ  r9   
is_successr:   )possible_urlr   head_requests      r=   validate_urlr&  $  sl    WXG	zz,RVW##z199j &&& s   AA 
A 
A#"A#c                Z    [        U [        5      =(       a    SU R                  SS5      ;   $ )Nupdate__type__r1   )r   r  r9   )vals    r=   is_prop_updater+  2  s$    c4 HXR1H%HHrE   c                  ^ ^^^^ Tc  / OTmTc  / OTm[         R                  " T 5      (       a%  [        R                  " T 5      UUUUU 4S j5       nU$ [        R
                  " T 5      (       a%  [        R                  " T 5      UUUUU 4S j5       nU$ [         R                  " T 5      (       a%  [        R                  " T 5      UUUUU 4S j5       nU$ [        R                  " T 5      UUUUU 4S j5       nU$ )Nc                   >#    T" U 0 UD6n T(       a  T" T6    UR                  5       I S h  vN nT(       a  T" T6   U7v   M8   N! [         a    T(       a  T" T6    g f = f7frI   )r  r  	r  r  r  r>  
after_argsafter_fnbefore_args	before_fnfs	       r=   asyncgen_wrapper*function_wrapper.<locals>.asyncgen_wrapperA  sq     $)&)H{+%-%7%7%99H
 j)   :)  *-s7   A#A AA A#A A A#A  A#c                 d   >#    T(       a  T" T6   T" U 0 UD6I S h  vN nT(       a  T" T6   U$  N7frI   rD   r  r  r>  r/  r0  r1  r2  r3  s      r=   async_wrapper'function_wrapper.<locals>.async_wrapperU  s8     ;'///H*%O 0s   0.0c               ?     >#    T" U 0 UD6n T(       a  T" T6    [        U5      nT(       a  T" T6   Uv   M*  ! [         a    T(       a  T" T6    g f = f7frI   )r  r  r.  s	       r=   gen_wrapper%function_wrapper.<locals>.gen_wrapperb  sf     $)&)H{+#H~H
 j) 
 %  *-s%   A7 AAAAAc                 H   > T(       a  T" T6   T" U 0 UD6nT(       a  T" T6   U$ rI   rD   r7  s      r=   wrapper!function_wrapper.<locals>.wrapperv  s-    ;'$)&)H*%OrE   )rq  isasyncgenfunction	functoolsr   r@   iscoroutinefunctionisgeneratorfunction)	r3  r2  r1  r0  r/  r4  r8  r;  r>  s	   `````    r=   function_wrapperrD  6  s     $+"K!)zJ!!!$$			 	 
	  		$	$Q	'	'			 	 
	 		$	$Q	'	'			 	 
	  
		 	 
	 rE   c                8   ^^^ UUU4S jnS n[        U UX4US9$ )Nc                D  > SSK Jn  UR                  R                  U 5        UR                  R                  T5        UR
                  R                  U5        UR                  R                  T5        T(       a&  UR                  R                  TR                  5        g g )Nr   LocalContext)gradio.contextrH  rU   r}   in_event_listenerevent_idrequestblocks_config)rU   rK  rH  rJ  rL  states      r=   r2  +get_function_with_locals.<locals>.before_fn  sy    /'&&**+<=!!(+  )&&**5+>+>? rE   c                     SSK Jn   U R                  R                  S5        U R                  R                  S 5        U R
                  R                  S 5        g )Nr   rG  F)rI  rH  rJ  r}   rL  rM  rG  s    r=   r0  *get_function_with_locals.<locals>.after_fn  sA    /&&**51  &""&&t,rE   )r2  r1  r0  )rD  )fnrU   rK  rJ  rL  rN  r2  r0  s      ```  r=   get_function_with_localsrS    s,    @- 
&	 rE   c                  #    [         R                  " 5        Vs/ s H  oUR                  5       4PM     nn/ n/ nU HY  u  pSU;  a  M  UR                  S5      u  pgX`;   d  M'  UR	                  U5        UR	                  U5        UR                  5         M[     [         R                  " USS06I S h  vN   U$ s  snf  N7f)N<gradio-sep>return_exceptionsT)r@   	all_tasksget_namer   r  cancelgather)task_idstasktasks	event_idsmatching_tasksr  task_idrK  s           r=   cancel_tasksra    s     181B1B1DE1DDMMO$1DEEIN
% JJ~6!!$'X&KKM  ...
AD
AAA F Bs"   CB:+C$AC3B?4Cc                F    U(       d  U R                  U SU SU 35        g g )Nr  rU  )set_name)r\  session_hashfn_indexrK  batchs        r=   set_task_namerg    s'    azhZHI rE   c                   ^ / nU  HT  m[        5       nU(       d  M  [        U4S jUR                  R                  5        5       5      nUR	                  U5        MV     U$ )Nc              3  X   >#    U  H  u  pUR                  5       T:X  d  M  Uv   M!     g 7frI   )
get_config)r}  r  ddeps      r=   r  +get_cancelled_fn_indices.<locals>.<genexpr>  s&      4da#8M4s   *	*)r   r  fnsr   r  )r  
fn_indices
root_blockre  rl  s       @r=   get_cancelled_fn_indicesrq    s]     J')
: (nn224 H h'  rE   c                    [         R                  " U 5      (       d  [         R                  " U 5      (       a  O[        U 5      (       a  U R                  n O0 $ [
        R                  " U 5      $ rI   )rq  
isfunctionismethodcallable__call__typingget_type_hints)rR  s    r=   rx  rx    sN    "!1!1"!5!5	"[[	  $$rE   c                   SSK Jn  SSKJnJn  SSKJn   UR                  U 5      nU(       d  gXe[        U   4;   nUU[        U   U[        U   4;   n[        R                  " U5      =(       a    [        Xb5      n	U=(       d    U	=(       d    U$ )Nr   )	EventData)OAuthProfile
OAuthToken)r*   F)gradio.helpersrz  gradio.oauthr{  r|  gradio.routesr*   r9   r   rq  isclassr  )
r  parameter_typesrz  r{  r|  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.IM66,6rE   c           	     0    [         R                  " U 5      n[        U 5      nSnSnSnUR                  R                  5        H  u  pU	R                  U	R                  :g  n
U	R                  U	R                  U	R                  4;   a%  [        X5      (       d  U
(       d  US-  nUS-  nMg  Mi  U	R                  U	R                  :X  a  UnM  U	R                  U	R                  :X  d  M  U
(       a  M  SU  3s  $    U(       a  SO
[        U5      nXV:X  a%  Xk:w  a   [        R                   " SU SU  SU S	35        X:  a   [        R                   " S
U SU  SU S	35        Xg:w  a'  X:  a!  [        R                   " SU SU  SU S	35        ggg! [         a     gf = f)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   r   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 )rq  rr  rX  rx  rs  r   ru  rw  kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr  VAR_POSITIONALKEYWORD_ONLYr   warningswarn)rR  r  inputs_as_dictrr  r  min_argsmax_argsinfinityr  paramhas_default	arg_counts               r=   check_function_inputs_matchr    s   %%b)	 %R(OHHH ++113mmu{{2::%//1L1LMM-dDD"MHA E ZZ5///HZZ5---kkMbTRR 4 $VI 5z!9"[STU	
  
*B2$kR[Q\\]^	
 	 4z)A"[QZP[[\]	
 !55  s   F 
FFc                       \ rS rSrS rS rSrg)TupleNoPrinti  c                    gNr1   rD   rP   s    r=   __repr__TupleNoPrint.__repr__      rE   c                    gr  rD   rP   s    r=   __str__TupleNoPrint.__str__  r  rE   rD   N)r4   rb   rc   rd   r  r  rf   rD   rE   r=   r  r    s    rE   r  c                       \ rS rSrS rS rSrg)MatplotlibBackendManangeri  c                z     SS K nUR                  5       U l        UR                  S5        g ! [         a     g f = f)Nr   agg)
matplotlibget_backend_original_backenduser+  )rQ   r  s     r=   	__enter__#MatplotlibBackendMananger.__enter__  s9    	%/%;%;%=D"NN5! 		s   *- 
::c                d     SS K nUR                  U R                  5        g ! [         a     g f = fNr   )r  r  r  r+  )rQ   exc_typeexc_valexc_tbr  s        r=   __exit__"MatplotlibBackendMananger.__exit__   s.    	NN4112 		s   " 
//)r  N)r4   rb   rc   rd   r  r  rf   rD   rE   r=   r  r    s    rE   r  c           
        [        5          SS KJn  SnSnUR                  SSS9  UR	                  SS9nUR                  SSS	U  S	3US
9  [        5       nUR                  UUSSSSS9  UR                  U5        UR                  S5        UR                  5       R                  S5      nUR                  S5      nXxS  n	[        R                  " SSU	[        R                  S9n	[        R                  " SSU	5      n	[        R                   " SU	5      n
U
(       a:  [#        U
R%                  S5      5      nX-  n[        R                  " SSU S3U	5      n	SU  S3nS S S 5        W W	 3$ ! , (       d  f       N= f)Nr      i,  mathtextcm)fontset){Gz?r  )figsize$)fontsizeTsvgtightg        )dpitransparentformatbbox_inches
pad_inchesr/   z<svg z<metadata>.*<\/metadata>r1   )flagsz width="[^"]+"zheight="([\d.]+)pt"r   zheight="[\d.]+pt"zheight="zem"z<span style='font-size: 0px'>z</span>)r  matplotlib.pyplotpyplotrcfigurer]  r   savefigcloseseekr   r5   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  )  sm   	"	$'z4(jjj.A!G9A: 	 	
 			#A;;=''0NN7+	J'665r8299U66+R:yy!7B<--a01F*Jvv$C&@(H 4G9GD	? 
%@ [
##A 
%	$s   EE((
E6c                d    [        [        R                  R                  [	        U 5      5      5      $ rI   )r   r3  r   abspathr   )r   s    r=   r  r  M  s    D	*++rE   c                    [        U 5      R                  5       [        U5      R                  5       p U R                  U5        g! [         a     gf = f)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_torX  )path_1path_2s     r=   is_in_or_equalr  Q  sM     V_,,.0G0G0IF6" s   A 
AAc                    SSK Jn  [        U [        [        45      (       a  [	        U 5      /n UR
                  R                  U  Vs/ s H  n[	        U5      R                  5       PM     sn5        gs  snf )aY  
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  a  sT    > 1%#t%%e!!e"De47??#4e"DE"Ds   #A2c                8    SSK Jn  [        XR                  5      $ )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9&<&<==rE   c                  ^  [        T [        [        [        45      (       d  g[        T [        5      (       a  T R                  m [        T [        5      (       a!  [        T 5      m T R                  5       (       d  g[        U 4S jU 5       5      $ )zR
Returns True if the file is a static file (i.e. is is in the static files list).
Fc              3  <   >#    U  H  n[        TU5      v   M     g 7frI   r  )r}  static_filer   s     r=   r  "_is_static_file.<locals>.<genexpr>  s     V+~i55   )r   r   r   r!   r   rg  r  )r   static_filess   ` r=   r  r    sk     i#tX!677)X&&NN	)S!!O	!!VVVVrE   z<[^
>]*(?:
[^
>]*)*>c                L    [         R                  " [        SU =(       d    S5      $ r  )r  r  HTML_TAG_RE)raw_htmls    r=   remove_html_tagsr    s    66+r8>r22rE   c                     [         R                  " 5       n SnU (       aW  [         R                  " U 5      nSUR                  [        R
                  S5      ;  a   U$ U R                  n US-  nU (       a  MW  U$ )z/
Find the first stack frame not inside Gradio.
r   z/gradio//r   )rq  currentframegetfiler  r3  sepf_back)framenfnames      r=   find_user_stack_levelr    sk       "E	A
&U]]266377 H 	Q % HrE   c                  ,   ^  \ rS rSrSrU 4S jrSrU =r$ )NamedStringi  a  
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                `   > [         TU ]  5         U(       a  [        U 5      U l        g SU l        g r  )rk   rl   r   r  )rQ   r  rt   s     r=   rl   NamedString.__init__  s!    !%CI	2	rE   )r  )r4   rb   rc   rd   r  rl   rf   r   r   s   @r=   r  r    s    . .rE   r  c               #  ,   #    Sn  SU  3v   U S-  n M  7f)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 r   rD   )r  s    r=   default_input_labelsr
    s)     
 	
A
qcl	Q s   c                    [         R                  R                  U 5      n[        R                  R                  [        R                  R                  UR                  5      5      S   nU(       a  USS $ S$ )z
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".
r   Nr1   )rS  r   rT  r3  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7rE   KVc                  P   ^  \ rS rSrSSU 4S jjjrSU 4S jjrS	U 4S jjrSrU =r$ )
LRUCachei  c                .   > [         TU ]  5         Xl        g rI   )rk   rl   max_size)rQ   r  rt   s     r=   rl   LRUCache.__init__  s    %rE   c                   > X;   a  U R                  U5        O([        U 5      U R                  :  a  U R                  SS9  [        TU ]  X5        g )NF)last)move_to_endr   r  popitemrk   __setitem__)rQ   r  r   rt   s      r=   r  LRUCache.__setitem__  sA    ;S!Y$--'LLeL$C'rE   c                "   > [         TU ]  U5      $ rI   )rk   __getitem__)rQ   r  rt   s     r=   r   LRUCache.__getitem__  s    w"3''rE   )r  )d   )r  r   )r  r  r   r  r`   r   )r  r  r`   r  )	r4   rb   rc   rd   rl   r  r   rf   r   r   s   @r=   r  r    s    & &(( (rE   r  c                 T    [        [        R                  R                  SS5      5      $ )NGRADIO_EXAMPLES_CACHEz.gradio/cached_examples)r   r3  r4  r9   rD   rE   r=   get_cache_folderr%    s    

68QRSSrE   c                $   ^ SU4S jjmT" X5      $ )Nc           	       > Uc  / n/ nX:X  a  U$ [        U 5      [        U5      La  UR                  SX!45        U$ [        U [        5      (       a7  UR	                  U 5      (       a!  UR                  SX![        U 5      S  45        U$ [        U [        5      (       a  [        [        U 5      [        U5      5      n[        U5       H#  nUR                  T" X   X   X%/-   5      5        M%     [        U[        U 5      5       H  nUR                  SX%/-   S 45        M     [        U[        U5      5       H  nUR                  SX%/-   X   45        M     U$ [        U [        5      (       ar  U  HA  nXa;   a"  UR                  T" X   X   X&/-   5      5        M*  UR                  SX&/-   S 45        MC     U H#  nX`;  d  M
  UR                  SX&/-   X   45        M%     U$ UR                  SX!45        U$ )Nr  r  deleteadd)r  r  r   r   r  r   r   minranger  r  )obj1obj2r   editscommon_lengthr  r  compare_objectss          r=   r0  diff.<locals>.compare_objects  s   <D<L:T$Z'LL)T01LdC  T__T%:%:LL(Ds4y{*;<=LdD!!D	3t95M=)_TWdgtczJK *=#d)4hs
D9: 5=#d)4eTCZ9: 5LdD!!;LLDIte|!TULL(D5L$!?@	 
 ?LL%ty!AB  Li,-rE   rI   rD   )oldnewr0  s     @r=   diffr4    s    &P 3$$rE   c                     [         R                  R                  S5      =(       d8    [        [	        [
        R                  " 5       5      S-  R                  5       5      $ )NGRADIO_TEMP_DIRr  )r3  r4  r9   r   r   tempfile
gettempdirr   rD   rE   r=   get_upload_folderr9    sC    ::>>+, 	h!!#	$x	/88:1 rE   c           
     :   / n[         R                  " U 5      n[        U 5      nUR                  R	                  5        H  u  pEUR
                  [         R                  R                  [         R                  R                  4;   a    U$ [        XC5      (       a  M\  UR                  [         R                  R                  L a'  UR                  USSUR                  US5      45        M  UR                  USUR                  UR                  US5      45        M     U$ )z
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)rq  rr  rx  rs  r   r  rv  r  VAR_KEYWORDr  ru  rw  r  r9   )rx  params_inforr  
type_hintsr  	parameters         r=   get_function_paramsr?    s    
 K!!$'I%J$//557>>,,))
 
   &d77 1 1 7 77eT:>>$3MNOtY..
tT0JK 8 rE   c                    [         R                  " U 5      R                  nU[         R                  R                  S [
        1;   a  / $ [        U5      [        L a  [        [        U5      5      $ U/$ rI   )
rq  rr  return_annotation	Signaturerw  r   r   r  r   r   )rx  return_hints     r=   get_return_typesrD  8  s]    ##D);;Kw((..h??	+%'H[)**=rE   c                    [         R                  " U 5      n[        R                  " US [        R
                  5      n[        U[        5      (       a  U$ [         R                  " U5      $ ! [         R                   a    U s $ f = f)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                    U S   $ )Nr   rD   xs    r=   r  +simplify_file_data_in_str.<locals>.<lambda>M  s    1V9rE   )	r7   r8   JSONDecodeErrorclient_utilstraverseis_file_obj_with_metar   r   r  )r   payloads     r=   simplify_file_data_in_strrO  D  ss    **Q- ##$l&H&HG '3::g  s   A, ,BBc                   ^  U 4S jnU$ )Nc               ?  "   >#    T" U 0 UD6v   g 7frI   rD   r  r  rR  s     r=   wrapped%sync_fn_to_generator.<locals>.wrappedU  s     $!&!!s   rD   rR  rS  s   ` r=   sync_fn_to_generatorrV  T  s    " NrE   c                   ^  U 4S jnU$ )Nc                8   >#    T" U 0 UD6I S h  vN 7v   g  N7frI   rD   rR  s     r=   rS  &async_fn_to_generator.<locals>.wrapped\  s     '''''s   	rD   rU  s   ` r=   async_fn_to_generatorrZ  [  s    ( NrE   c                0   ^  [        T 5      U 4S j5       nU$ )z|Turn a function into an async function.
Useful for internal event handlers defined as lambda functions used in the codebase
c                    >#    T" U 0 UD6$ 7frI   rD   )r  r  r3  s     r=   rD  &async_lambda.<locals>.function_wrapperg  s     $!&!!s   	r   )r3  rD  s   ` r=   async_lambdar^  b  s#    
 1X" " rE   c                  @    \ rS rSrSrS\-  rS\-  rS\-  rS\-  rSr	g)FileSizein  r   i   rD   N)
r4   rb   rc   rd   BKBMBGBTBrf   rD   rE   r=   r`  r`  n  s+    	A	B	B	B	BrE   r`  c                6   [        U [        5      (       d  U c  U $ U R                  SS5      n [        S [	        U 5       5       [        U 5      5      n[        U S U 5      XS  R                  5       p2[        [        US 5      nU(       d  [        SU 35      eXB-  $ )N r1   c              3  X   #    U  H   u  pUR                  5       (       a  M  Uv   M"     g 7frI   )isdigit)r}  r  r  s      r=   r  #_parse_file_size.<locals>.<genexpr>}  s     :tqaiiks   *	*zInvalid file size unit: )
r   r   r  r  r  r   upperr   r`  rX  )sizelast_digit_indexsize_intunitmultiples        r=   _parse_file_sizerq  v  s    $<<R D:y:CI //0148I3J3P3P3Rdxt,H3D6:;;rE   c                `  ^ SSK Jm  [        U4S jU 5       5      nSnSnSU ;  a  [        S5      eU S    Ha  nUS    HU  n[	        U[
        [        45      (       d  M   [        U5      S:X  d  M1  US	   S
:H  nU(       a    MK  US	   S:H  nU(       d  MT    M_     Mc     U=(       d    U=(       d    U$ )z@
Determines whether a heartbeat is required for a given config.
r   )Statec              3  <   >#    U  H  n[        UT5      v   M     g 7frI   )r   )r}  r&  rs  s     r=   r  $connect_heartbeat.<locals>.<genexpr>  s     A&Jue,,&r  Fr  zPDependencies not found in config. Cannot determine whetherheartbeat is required.r     r   unloadstream)r  rs  r  rX  r   r   r  r   )r   rU   	any_state
any_unload
any_streamrl  targetrs  s          @r=   connect_heartbeatr}    s     (A&AAIJJV#%
 	

 n%)nF&4-00S[A5E#AY(2
#AY(2
: % & 0
0j0rE   c           
     (   [         R                  " 5       n[        U [        [        [
        [        45      (       a  U nGO[        U [        5      (       aC  [        [        U R                  5       S S9 VVs/ s H  u  p4U[        U5      4PM     snn5      nO[        U [        [        45      (       a  [        S U  5       5      nO[        U [        5      (       a  [        S [        U [        S9 5       5      nO\[        U [        5      (       a$  [        [        U 5      5      R!                  S5      nO#[        [#        U 5      5      R!                  S5      nUR%                  ['        U5      R!                  S5      5        UR)                  5       $ s  snnf )z2Compute a hash for a deeply nested data structure.c                    [        U S   5      $ r  )hashrG  s    r=   r  deep_hash.<locals>.<lambda>  s    d1Q4jrE   )r  c              3  8   #    U  H  n[        U5      v   M     g 7frI   	deep_hashr}  rH  s     r=   r  deep_hash.<locals>.<genexpr>  s     0CqillCr  c              3  8   #    U  H  n[        U5      v   M     g 7frI   r  r  s     r=   r  r    s     B,Aqill,Ar  r/   )hashlibsha256r   r   r  r   r  r  r  sortedr   r  r   r}   r  r   encoder   r(  repr	hexdigest)r  hasherr   kr   s        r=   r  r    s)   ^^F#UC/00	C		 #399;4HIIDA IaL!I
 
C$	'	'0C00	C		BF3D,ABB	C	"	"DI%%g.BsG##G,
MM$u+$$W-.s   5F
c                   SS 0nU=(       d    [        U [        5      nU(       aa  [        U [        5      (       a>  U R                  US'   U R                  US'   U R                  US'   U R
                  US'   U$ [        U 5      US'   U$ )Nr   durationvisibletitle)r   r#   messager  r  r  r   )r   
show_errorcontents      r=   error_payloadr    s     6=dOG7z%7JeU##$}}GG"'..GJ!&GI${{GG N  #5zGGNrE   c                  B    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
rg)UnhashableKeyDicti  z
Essentially a list of key-value tuples that allows for keys that are not hashable,
but acts like a dictionary for convenience.
c                    / U l         g rI   datarP   s    r=   rl   UnhashableKeyDict.__init__  s	    	rE   c                j    U R                    H  u  p#[        X!5      (       d  M  Us  $    [        U5      erI   )r  r  KeyError)rQ   r  r  r   s       r=   r   UnhashableKeyDict.__getitem__  s.    IIDA!!!  smrE   c                    [        U R                  5       H*  u  nu  pE[        XA5      (       d  M  X4U R                  U'     g    U R                  R                  X45        g rI   )r  r  r  r  )rQ   r  r   r  r  r  s         r=   r  UnhashableKeyDict.__setitem__  sN    "499-IAv!!! #|		! . 			#&rE   c                    [        U R                  5       H'  u  nu  p4[        X15      (       d  M  U R                  U	   g    [        U5      erI   )r  r  r  r  )rQ   r  r  r  r  s        r=   __delitem__UnhashableKeyDict.__delitem__  s@    "499-IAv!!!IIaL . smrE   c                (    S U R                    5       $ )Nc              3  *   #    U  H	  u  pUv   M     g 7frI   rD   )r}  r  r  s      r=   r  -UnhashableKeyDict.__iter__.<locals>.<genexpr>  s     (idais   r  rP   s    r=   __iter__UnhashableKeyDict.__iter__  s    (dii((rE   c                ,    [        U R                  5      $ rI   )r   r  rP   s    r=   __len__UnhashableKeyDict.__len__  s    499~rE   c                P    U R                    VVs/ s H  u  pUPM	     snn$ s  snnf rI   r  )rQ   r  r   s      r=   as_listUnhashableKeyDict.as_list  s     "ii(idai(((s   "r  N)r4   rb   rc   rd   r  rl   r   r  r  r  r  r  rf   rD   rE   r=   r  r    s*    
'))rE   r  c                  ^ [         R                  R                  [         R                  R                  4 Vs/ s H  o"c  M  US:w  d  M  UPM     nn[        R
                  " U5      m[         R                  R                  U T5      n[        U4S jU 5       5      (       d@  [         R                  R                  T5      (       d  TS:X  d  TR                  S5      (       a
  [        5       eU$ s  snf )zpSafely path to a base directory to avoid escaping the base directory.
Borrowed from: werkzeug.security.safe_joinr  c              3  ,   >#    U  H	  oT;   v   M     g 7frI   rD   )r}  r  r   s     r=   r  safe_join.<locals>.<genexpr>  s     4|8O|r  z..z../)r3  r   r  altsep	posixpathnormpathjoinr  isabsr  r$   )	directoryr   r  _os_alt_sepsfullpathr   s        @r=   	safe_joinr    s     RWW^^44CSVJ4   !!$'Hww||Ix0H4|44477==""tu%%  Os   C.C.
C.c                   ^  [        U 4S jU 5       5      nU(       a  g[        U 4S jU 5       5      (       a  g[        U 4S jU 5       5      (       a  gg)Nc              3     >#    U  H?  n[        [        T5      R                  5       [        U5      R                  5       5      v   MA     g 7frI   )r  r   r=  )r}  blocked_pathr   s     r=   r  "is_allowed_file.<locals>.<genexpr>  s;      )L 	s4y(#l*;*A*A*CDD)s   AA
)Fin_blocklistc              3  <   >#    U  H  n[        TU5      v   M     g 7frI   r  )r}  allowed_pathr   s     r=   r  r         
P-,>$---r  )Tallowedc              3  <   >#    U  H  n[        TU5      v   M     g 7frI   r  )r}  created_pathr   s     r=   r  r    r  r  )Tcreated)Fnot_created_or_allowed)r  )r   blocked_pathsallowed_pathscreated_pathsr  s   `    r=   is_allowed_filer    sO      ) L $

P-
PPP

P-
PPP*rE   c                 8   [         R                  R                  S5      n U (       a  U $ [        R                  " S5      nU(       a  U$  [
        R                  S:X  am  [        R                  " SS/5      R                  5       R                  5       R                  S5      S   n[         R                  R                  U5      (       a  U$ O4[        R                  " SS/5      R                  5       R                  5       $ [
        R                  SS	S
S/nU H+  n[         R                  R                  U5      (       d  M)  Us  $    [         R                  R                  SS5      nUR                  [         R                   5      nU Ha  n[         R                  R#                  U[
        R                  S:X  a  SOS5      n[         R                  R                  U5      (       d  M_  Us  $    [%        S5        [%        S5        g ! [        R                   a     GNf = f)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PATHr1   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.)r3  r4  r9   shutilr  r   platform
subprocesscheck_outputr5   r6   r   r   rg  CalledProcessError
executablepathsepr  r   )	env_node_pathwhich_node_pathwindows_pathcommon_paths	node_pathenv_path	path_dirsr  	full_paths	            r=   get_node_pathr    s   JJNN#56Mll6*O<<7"''&(9:vq"  ww~~l++## , **GV+<=DDFLLNN 	-3L "	77>>)$$ "
 zz~~fb)Hrzz*I	GGLLS\\W%<z&
	 77>>)$$  

GH	 	K A (( s   	A?H 
3H HHc                ^    U c  / $ [        U [        [        45      (       a  [        U 5      $ U /$ rI   )r   r   r  r   s    r=   none_or_singleton_to_listr  V  s.    }	%$''E{7NrE   c           	        [        [        R                  R                  S5      R	                  [        [        S5      U -  5      5      5      n[        U5      R                  5       (       a  [        U5        U$ [        SU  35      e)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   rg  r  rX  )	icon_name	icon_paths     r=   get_icon_pathr  ^  sq     !!(+44Sg9R5STI I#
,YK8
99rE   c                r    0 nU  H.  u  p#[        US5      (       a  UR                  5       X'   M*  X1U'   M0     U$ )zZ
A utility function to convert a dataclass that includes pydantic fields to a dictionary.

model_dump)hasattrr  )r   rk  r  r   s       r=   dict_factoryr  p  s@     	A
5,''%%'AFcF	 
 HrE   )r`   r   )r`   zasyncio.Lock)r`   zasyncio.Event)r   r   )r   r   r`   zModuleType | None)r   rh   )r  r   r  r   r`   r   )r   r&   r%  r&   r   )r`   
str | None)ra  r   r`   r   )rx  r   r`   	list[Any])r  r   r`   r   ))r   )r  r   r  r   r  r  )F)r  r  r  r   r`   r  )r  zlist[Any] | Anyr`   r   )r`   z*list[type[Component] | type[BlockContext]])r  r   r`   z$type[Component] | type[BlockContext])rx  r   )r   z
Path | str)r   str | floatr`   r  )rt  r  r`   r  )r  r   r  r   )r$  r   r`   r   )NNNN)
r3  r   r2  Callable | Noner1  Iterable | Noner0  r  r/  r  )rR  r   rU   r&   rK  r  rJ  r   rL  zRequest | NonerN  zSessionState | None)r[  zset[str]r`   r   )rd  r   re  r   rK  r   rf  r   )r  zlist[dict[str, Any]]r`   z	list[int])rR  r   r  r   r  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   )rx  r   r`   z list[tuple[str, bool, Any, Any]])rx  r   r`   r   )r3  r   r`   r   )rl  zstr | int | Noner`   z
int | None)r   r   r`   r   )r   zBaseException | Noner  r   r`   z$dict[str, bool | str | float | None])r  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  
__future__r   r   r@   r  rA  r  r   importlib.resourcesimportlib.utilrq  r7   json.decoderr3  r2   r  r  r  r  r   r7  	threadingr   r   rw  urllib.parserS  ri  r  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utilsrK  rY  r
  gradio_client.documentationr   typing_extensionsr   r  rI  r   r  r   r    r!   r"   gradio.exceptionsr#   r$   r$  r%   r&   r  r(   r  r)   r*   gradio.state_holderr+   r,   r-   r>   rF   rK   rM   rh   r   r   r   r   r   r  r  r   r/  r5  r?  rB  rI  rM  rd  r   r  dirnamer   rh  ro  ry  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  r+  rD  rS  ra  rg  rq  rx  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r   r  r
  r  r  r  r  r%  r4  r9  r?  rD  rO  rV  rZ  r^  r`  rq  r}  r  r  r  r  r  r  r  r  r  rD   rE   r=   <module>r     sF    " 
           	   	   
         # #  &    &	 	 	  *   0 '  -  62+*0cNCL	
'3 '$($ ($V!S ! 4 	!H^B.&2R" 2* bggoofoo>P "& NWHH(8HEJHV	8:98-
 
 !      I "&#' $"&III !I 	I
  IX  	
  B J
&%7(%
P5  &!$H,  
"F "FJ>W jj2BII>3
.# 
.8 CLCL({GAqDM ( T)%X2	 	  180-1) $) $)N(+
+'+ (+ (	+
+*9x:$
rE   