
    ;3h                    F   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mZmZmZ d dlmZmZ d dlmZ d dlmZ d dlmZmZm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%m&Z' d d
l(m)Z)m*Z*m+Z+m,Z, d dl-m&Z&m.Z. d dl/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z>m?Z?  ej                         5   ej                  d       d dlBmCZC ddd       e.j                  rkd dlEZFd dlGZG G d de j                        ZI G d de j                        ZK eK       ZL G d de j                        ZN G d de j                        ZP eP       ZQndZLdZQ e j                  eL      ZS ej                  eU      ZVerd dlWmXZX dDdZYdEdZZdFdGdZ[d  Z\d! Z]dFd"Z^ e=       j                  d#      Z`dHdId$ZadJd%ZbdKd&ZcdHdLd'Zd	 	 dM	 	 	 	 	 	 	 	 	 dNd(Ze	 dO	 	 	 	 	 	 	 dPd)Zf	 	 	 	 	 	 	 	 	 	 dQd*ZgdRd+ZhdSd,Zig d-ZjdTd.Zk ed/      ZldHdUd0ZmdVd1ZndVd2ZodVd3ZpepZq	 dW	 	 	 	 	 	 	 dXd4Zr	 	 	 	 	 	 dYd5ZsdZd6Zt	 	 	 d[	 	 	 	 	 d\d7Zud]d8Zv	 	 	 d[	 	 	 	 	 	 	 d^d9Zwd_d:Zxd`d;Zy	 da	 	 	 	 	 	 	 dbd<Zzdcd=Z{d> Z|ddd?Z}ded@Z~dfdAZdgdBZdhdCZy# 1 sw Y   xY w)i    )annotationsN)	AwaitableCallable	Coroutine	lru_cachewraps)BytesIO)Path)TYPE_CHECKINGAnyTypeVar)urlparse)utils)ImageImageOpsImageSequencePngImagePlugin)r   
wasm_utils)LocalContext)FileDataGradioModelGradioRootModelJsonData)ErrorInvalidPathError)
API_PREFIX)abspathget_hash_seedget_upload_folderis_in_or_equalignore)AudioSegmentc                      e Zd ZddZd Zy)Urllib3ResponseSyncByteStreamc                    || _         y Nresponseselfr)   s     W/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/processing_utils.py__init__z&Urllib3ResponseSyncByteStream.__init__.   	    $DM    c              #  X   K   | j                   j                  d      E d {    y 7 w)NT)decode_content)r)   streamr+   s    r,   __iter__z&Urllib3ResponseSyncByteStream.__iter__1   s!     }}++4+@@@s    *(*N)r)   zurllib3.HTTPResponsereturnNone)__name__
__module____qualname__r-   r4    r/   r,   r%   r%   -   s    	%	Ar/   r%   c                      e Zd Zd ZddZy)Urllib3Transportc                6    t        j                         | _        y r'   )urllib3PoolManagerpoolr3   s    r,   r-   zUrllib3Transport.__init__5   s    ++-DIr/   c                   t        |j                        }t        |j                        }t        |j                        }|dv rd n|j                         }| j                  j                  ||||d      }|j                  j                         }|j                  d       t        j                  |j                  |t        |            S )NGETHEADF)headersmethodurlbodypreload_contentzcontent-encodingstatus_coderE   r2   )strrG   rF   dictrE   readr@   requestcopydiscardhttpxResponsestatusr%   )r+   rO   rG   rF   rE   rH   r)   response_headerss           r,   handle_requestzUrllib3Transport.handle_request8   s    gkk"C(F7??+G!_44',,.Dyy(( % ) H  (//446$$%78>>$OO(4X> r/   NrO   zhttpx.Requestr5   zhttpx.Response)r7   r8   r9   r-   rV   r:   r/   r,   r<   r<   4   s    	.	r/   r<   c                      e Zd ZddZd Zy)"PyodideHttpResponseAsyncByteStreamc                    || _         y r'   r(   r*   s     r,   r-   z+PyodideHttpResponseAsyncByteStream.__init__U   r.   r/   c               Z   K   | j                   j                          d {    y 7 wr'   )r)   bytesr3   s    r,   	__aiter__z,PyodideHttpResponseAsyncByteStream.__aiter__X   s     ++----s   +)	+N)r)   zpyodide.http.FetchResponser5   r6   )r7   r8   r9   r-   r]   r:   r/   r,   rY   rY   T   s    	%	.r/   rY   c                      e Zd Z	 	 	 	 ddZy)PyodideHttpTransportc                  K   t        |j                        }|j                  }t        |j                        }|d= |dv rd n|j                          d {   }t        j                  j                  ||||       d {   }t        j                  |j                  |j                  t        |            S 7 d7 ;w)Nz
user-agentrB   )rF   rE   rH   rJ   )rL   rG   rF   rM   rE   areadpyodidehttppyfetchrR   rS   rT   rY   )r+   rO   rG   rF   rE   rH   r)   s          r,   handle_async_requestz)PyodideHttpTransport.handle_async_request\   s      gkk"C^^F7??+G %!_44:OD$\\11FG$ 2  H >>$OO ((9(C 	 ;Ps$   AB>B:*B> B<:B><B>NrW   )r7   r8   r9   re   r:   r/   r,   r_   r_   [   s    	"	 	r/   r_   )	transport)Blockc                    t        | t              r0| j                  d      r| d   }nt        j                  | d         }n| }t        j                  t        |            S )zUConverts a base64 string or dictionary to a binary string that can be sent in a POST.datapath)
isinstancerM   getclient_utilsencode_url_or_file_to_base64base64	b64decodeextract_base64_data)x	base64strs     r,   	to_binaryrt      sP    !T55=&	I$AA!F)LI	/	:;;r/   c                ,    | j                  dd      d   S )z;Just extracts the base64 data from a general base64 string.,   )rsplit)rr   s    r,   rq   rq      s    88CBr/   c                    |xs d}t               5 }| j                  ||       |j                         }d d d        t        t	        j
                        d      }d|xs d d| S # 1 sw Y   4xY w)Npngformatutf-8zdata:image/z;base64,)r
   savefiggetvaluerL   ro   	b64encode)pltr}   fmtoutput_bytes
bytes_data
base64_strs         r,   encode_plot_to_base64r      sv    
/EC	 -lL-!**,
- V%%j17;J5)*>>	- -s   $A((A1c                >    d| j                   v r| j                   d   S y )Nexif)info)	pil_images    r,   get_pil_exif_bytesr      s"    ~~f%%  r/   c                    t        j                         }| j                  j                         D ]9  \  }}t	        |t
              st	        |t
              s(|j                  ||       ; |S r'   )r   PngInfor   itemsrk   rL   add_text)r   metadatakeyvalues       r,   get_pil_metadatar      sZ    %%'Hnn**, *
Uc3Juc$:c5)* Or/   c           	        t               5 }|j                         dk(  rMt        j                  |       D cg c]  }|j	                          }}|d   j                  ||d|dd  d       nH|j                         dk(  rdt        |       i}nt        |       }|rd|ini } | j
                  ||fi | |j                         cd d d        S c c}w # 1 sw Y   y xY w)	Ngifr   Trw   )r}   save_allappend_imagesloopr{   pnginfor   )	r
   lowerr   IteratorrP   saver   r   r   )r   r}   r   frameframesparamsr   s          r,   encode_pil_to_bytesr      s    	 'l<<>U"0=0F0Fy0QRuejjlRFR1INN$QRj   ||~&#%5i%@A))4+/&$RINN<:6:$$&#' 'R' 's   +CCA6CCCr~   c                *   t        j                         j                  t               t	        | d      5 t        fdd      D ]  }j                  |        	 d d d        j                         S # 1 sw Y   j                         S xY w)Nrbc                 @    j                   j                  z        S r'   )rN   
block_size)chunk_num_blocksfshas   r,   <lambda>zhash_file.<locals>.<lambda>   s    !&&)9CNN)J"K r/   r/   )hashlibsha256update	hash_seedopeniter	hexdigest)	file_pathr   chunkr   r   s    ` @@r,   	hash_filer      sv    
..
CJJy	i	 !KSQ 	EJJu	 ==? ==?s   (A::Bc                    t        j                         }|j                  t               |j                  | j	                  d             |j                         S )Nr~   )r   r   r   r   encoder   )rG   r   s     r,   hash_urlr      s;    
..
CJJyJJszz'"#==?r/   c                    t        j                         }|j                  t               |j                  |        |j	                         S r'   )r   r   r   r   r   )r\   r   s     r,   
hash_bytesr      s2    
..
CJJyJJu==?r/   c                .   t        j                         }|j                  t               t	        dt        |       ||j                  z        D ]7  }| ||||j                  z  z    }|j                  |j                  d             9 |j                         S )Nr   r~   )	r   r   r   r   rangelenr   r   r   )base64_encodingr   r   iri   s        r,   hash_base64r      s    
..
CJJy1c/*,<s~~,MN )q1'7#..'H#HI

4;;w'() ==?r/   c                   t        | |      }t        |      t        |      z  }|j                  dd       t	        || d| z  j                               }|| d| z  j                         j                  |       |S )NTexist_okparents.)r   r   r   mkdirrL   resolvewrite_bytes)img	cache_dirnamer}   r   temp_dirfilenames          r,   save_pil_to_cacher      s     %S&1JIJ!77HNND$N/H$q11::<=H4&&""++-99*EOr/   c                |    t        j                  t        | t        j                  d            }t        |||      S )NF)
force_copyr|   )r   	fromarray_convertnpuint8r   )arrr   r}   r   s       r,   save_img_array_to_cacher      s.     bhh5 IJIY	&AAr/   c                    t        |      t        | j                               z  }|j                  dd       t	        |d| z  j                               }t        || ||       |S )NTr   zaudio.r|   )r   r   tobytesr   rL   r   audio_to_file)ri   sample_rater}   r   r   r   s         r,   save_audio_to_cacher      s_     IDLLN!;;HNND$N/Hx0099;<H+tXf=Or/   c                    t        |      t        |       z  }|j                  dd       |t        |      j                  z  }|j	                  |        t        |j                               S )NTr   )r   r   r   r   r   rL   r   )ri   	file_namer   rj   s       r,   save_bytes_to_cacher   
  sX    	?Z--DJJdJ+$y/&&&DTt||~r/   c                :   t        |       }t        |      |z  }|j                  dd       t        j                  t        |       j
                        }t        t        ||z              }t        |      j                         st        j                  | |       |S )zReturns a temporary file path for a copy of the given file path if it does
    not already exist. Otherwise returns the path to the existing temp file.Tr   )r   r   r   rm   !strip_invalid_filename_charactersr   rL   r   existsshutilcopy2)r   r   r   r   full_temp_file_paths        r,   save_file_to_cacher     s     #HI)HNND$N/99$y/:N:NODgho67#$++-Y 34r/   )zhf.cozhuggingface.cozcas-bridge-direct.xethub.hf.coc                    	 t        j                  |       }|j                  xs6 |j                  xs( |j                  xs |j
                  xs |j                   S # t        $ r Y yw xY w)NF)	ipaddress
ip_address
is_privateis_loopbackis_link_localis_multicastis_reserved
ValueError)ipip_objs     r,   is_public_ipr   -  sz    
%%b) "!!"##" """ !!
 	
  s   AA 	A('A(Tc                     	 	 	 	 d fd}|S )Nc                P     t              t               d fd              }|S )N)maxsizec                 :    t        j                   | i |      S r'   )asynciocreate_task)argskwargs
async_funcs     r,   wrapperz3lru_cache_async.<locals>.decorator.<locals>.wrapperB  s      &&z4'B6'BCCr/   )r   r   r   r   r5   zAwaitable[T]r   )r   r   r   s   ` r,   	decoratorz"lru_cache_async.<locals>.decorator?  s2     
7	#	z		D 
 
$	D r/   )r   z%Callable[..., Coroutine[Any, Any, T]]r5   zCallable[..., Awaitable[T]]r:   )r   r   s   ` r,   lru_cache_asyncr   >  s     9	$ r/   c                  K   t        |      t        |       z  }|j                  dd       t        |       }|j                  j                  d      }t        j                  t        |      j                        xs d}t        t        ||z              }t        |      j                         r|S |j                  }t        j                  | t        t                d {   }|j"                  rn|j$                  d   }	t        |	      }
|
j                  s|j&                   d| |	 }	t        j                  |	t        t                d {   }|j"                  rn|j(                  dk7  rt+        d	|j(                         t-        j.                  |d
      4 d {   }|j1                         2 3 d {   }|j3                  |       d {    #7 7 7 ;7 $7 6 d d d       d {  7   |S # 1 d {  7  sw Y   |S xY ww)NTr   /file)domain_whitelist
_transportLocationz://   z&Failed to download file. Status code: wb)r   r   r   r   rj   rstriprm   r   r   rL   r   r   hostnameshrl   PUBLIC_HOSTNAME_WHITELISTasync_transportis_redirectrE   schemerK   	Exceptionaiofilesr   aiter_byteswrite)rG   r   r   
parsed_url	base_pathr   r   r  r)   redirect_urlredirect_parsedr   r   s                r,   async_ssrf_protected_downloadr  L  s    I#.HNND$N/#J&&s+I66tI7K7KLVPV  gh&9:; '')""""HVV7O H 

''
3"<0''(//0H:l^LL6&
 
 

 s"@AUAU@VWXX}}0$7 ! !1#//1 	! 	!%''%.  -
!	!  2! ! ! 	! ! ! s   CH G!A,HGHAH G!H$G65G"9G:G"=G6G G6HHHG" G6"G6#H.G1/H6H	<G?=H	Hc                   t        |      t        |       z  }|j                  dd       t        j                  t        |       j
                        }t        t        ||z              }t        j                  d| d      5 }t        |d      5 }|j                         D ]  }|j                  |        	 d d d        d d d        t        d| dt        j                  j!                  |       d       t"        j%                  d| dt        j                  j!                  |       d       |S # 1 sw Y   {xY w# 1 sw Y   xY w)	NTr   rC   )follow_redirectsr  zDownloaded z (z bytes))r   r   r   rm   r   r   rL   r   sync_clientr2   r   iter_rawr  printosrj   getsizelogr   )rG   r   r   r   r   rr   r   s           r,   unsafe_downloadr  v  s+   I#.HNND$N/==d3innMHgh&9:; 	5#=AB $'+,ZZ\ 	EGGEN		  

)*"RWW__=P-Q,RRYZ HH
)*"RWW__=P-Q,RRYZ    s$   D='D17D=1D:	6D==Ec                p    t         j                  rt        | |      S t        j                  t
        | |      S r'   )r   IS_WASMr  rm   synchronize_asyncr  )rG   r   s     r,   ssrf_protected_downloadr"    s2    sI..--)3	
 	
r/   c                   t        |       }t        |      |z  }|j                  dd       t        j                  |       }|rt        j
                  |      }n
|rd| }nd}t        t        ||z              }t        |      j                         s@t        j                  |       \  }}t        |d      5 }|j                  |       ddd       |S |S # 1 sw Y   |S xY w)zConverts a base64 encoding to a file and returns the path to the file if
    the file doesn't already exist. Otherwise returns the path to the existing file.
    Tr   zfile.r   r  N)r   r   r   rm   get_extensionr   rL   r   r   decode_base64_to_binaryr   r  )	r   r   r   r   guess_extensionr   ri   _fbs	            r,   save_base64_to_cacher)    s     ?+HI)HNND$N/"00AO BB9M		O,-		gh&:;<#$++-66Ga%t, 	HHTN	 	 s   8CC c                $    |j                  |       S )zThis method has been replaced by Block.move_resource_to_block_cache(), but is
    left here for backwards compatibility for any custom components created in Gradio 4.2.0 or earlier.
    )move_resource_to_block_cache)url_or_file_pathblocks     r,   r+  r+    s     --.>??r/   c                V    dd}t        j                  | |t         j                         y )Nc                    | j                  dd      x}r:t        j                  |      s$t        |t	                     st        d| d      y y y )Nrj    zFile z3 is not in the cache folder and cannot be accessed.)rl   rm   is_http_url_liker!   r    r   )drj   s     r,   	_in_cachez+check_all_files_in_cache.<locals>._in_cache  s]    UU62&&T& 11$7"4):)<=vPQ  > 8 'r/   r2  rM   )rm   traverseis_file_obj)ri   r3  s     r,   check_all_files_in_cacher7    s!     $	<+C+CDr/   c                    dddfd}t        | t        t        f      r| j                         } t	        j
                  | |t        j                        S )  Move any files in `data` to cache and (optionally), adds URL prefixes (/file=...) needed to access the cached file.
    Also handles the case where the file is on an external Gradio app (/proxy=...).

    Runs after .postprocess() and before .preprocess().

    Args:
        data: The input or output data for a component. Can be a dictionary or a dataclass
        block: The component whose data is being processed
        postprocess: Whether its running from postprocessing
        check_in_upload_folder: If True, instead of moving the file to cache, checks if the file is in already in cache (exception if not).
        keep_in_cache: If True, the file will not be deleted from cache when the server is shut down.
    c                    t         j                  j                         x}|j                  sGt	        j
                  | j                        d   dk(  r!t        j                  | j                  g       y y y Nr   zimage/svg+xml	r   blocksrl   
is_running	mimetypes
guess_typerj   r   set_static_pathspayloadr=  s     r,   _mark_svg_as_safez.move_files_to_cache.<locals>._mark_svg_as_safe  c     $**..00V9ARAR##GLL1!4G""GLL>2 H BSr/   c                   t        di | }|j                  r3
r1t        j                  |j                        r|j                  |_        nt        j                  |      rnj                  st        j                  |j                        st        |j                         |j                  sVj                  |j                        }|t        d      ||_        	r%j                  j                  |j                         |j                  r	t         dnt         d}j                  r5j                  j                  d      }t         d| | |j                   }nYt        j                  |j                        s|j                  j!                  |       r|j                   }n| |j                   }||_         |       |j#                         S Nz/Did not determine a file path for the resource.z/stream/z/file=r   z/proxy=r:   )r   rG   rm   r1  rj   r   is_static_file	proxy_url_check_allowed	is_streamr+  r   keep_in_cacheaddr   r  
startswith
model_dumpr2  rC  temp_file_path
url_prefixrI  rG   rD  r-  check_in_upload_folderrL  postprocesss         r,   _move_to_cachez+move_files_to_cache.<locals>._move_to_cache  s   -Q-
 ;;;<+H+H+U";;GL!!'*00>w||-CD$$!&!C!CGLL!Q!)$%VWW- ''++GLL9 (/'8'8zl(#F>S 	 ??..s3IL	{:,w||nMC**7<<8GLL<S<Sl=
 \\NCL/C'"!!##r/   rC  r   r4  )rk   r   r   rO  rm   r5  is_file_obj_with_metari   r-  rT  rS  rL  rU  rD  s    ```` @r,   move_files_to_cacherY    sP    (3$$ $$L $+67   nl@@ r/   c                    t         j                  j                         }||j                  sy t	        j
                         }t	        j                         g}|rg }n5|j                  t        j                         t        j                         gz   }t	        j                  ||j                  ||      \  }}|sd| d}|dk(  r-|ddj                  |j                         dz  }t#        |      |r|dz  }t#        |      |d	z  }|d
z  }|dz  }|dt        j                          dt        j                          dz  }|dt        |j                          dz  }t#        |      t	        j$                  |t        j                               rF|j&                  j)                  d      r*t+         fd|j                  D              st#        d      y y y )N)blocked_pathsallowed_pathscreated_pathszCannot move z! to the gradio cache dir because in_blocklistz+it is located in one of the blocked_paths (z, z).zit was not uploaded by a user.z3it was not created by the application or it is not zQlocated in either the current working directory or your system's temp directory. zOTo fix this error, please ensure your function returns files located in either zthe current working directory (z!), your system's temp directory (z) zor add z, to the allowed_paths parameter of launch().r   c              3  6   K   | ]  }t        |        y wr'   )r!   ).0allowed_pathrj   s     r,   	<genexpr>z!_check_allowed.<locals>.<genexpr><  s      
3?N4.
s   zDotfiles located in the temporary directory cannot be moved to the cache for security reasons. If you'd like to specifically allow this file to be served, you can add it to the allowed_paths parameter of launch().)r   r=  rl   has_launchedr   r   r    r\  r  getcwdtempfile
gettempdiris_allowed_filer[  joinrL   parentr   r!   r   rN  any)	rj   rS  r=  abs_pathr]  r\  allowedreasonmsgs	   `        r,   rJ  rJ    s     $$&F~V00}}T"H,,./M ,,		X=P=P=R/SS++**##	OGV XJ&GH^#@6K_K_A`@aacddC s## $33C s## HHCffCddC4RYY[MAbckcvcvcxbyy{||CWS122^__Cs##Xryy{3MM$$S) 
CICWCW
 
 E
 	
	
 * 	4r/   c                   K   dddfd}t        | t        t        f      r| j                         } t	        j
                  | |t        j                         d{   S 7 w)r9  c                    t         j                  j                         x}|j                  sGt	        j
                  | j                        d   dk(  r!t        j                  | j                  g       y y y r;  r<  rB  s     r,   rD  z4async_move_files_to_cache.<locals>._mark_svg_as_safeZ  rE  r/   c                  K   t        di | }|j                  r3
r1t        j                  |j                        r|j                  |_        nt        j                  |      rnj                  st        j                  |j                        st        |j                         |j                  s^j                  |j                         d {   }|t        d      ||_        	r%j                  j                  |j                         |j                  r	t         dnt         d}j                  r5j                  j                  d      }t         d| | |j                   }nXt        j                  |j                        s|j                  j!                  |       r|j                  }n| |j                   }||_         |       |j#                         S 7 wrG  )r   rG   rm   r1  rj   r   rH  rI  rJ  rK  "async_move_resource_to_block_cacher   rL  rM  r   r  rN  rO  rP  s         r,   rU  z1async_move_files_to_cache.<locals>._move_to_cacheb  s    -Q-
 ;;;<+H+H+U";;GL!!'*00>w||-CD$$','O'OLL( " ")$%VWW- ''++GLL9 (/'8'8zl(#F>S 	 ??..s3IL	{:,w||nMC**7<<8GLL<S<Sl=
 ,,CL/C'"!!##/"s   CG(G%DG(NrV  r4  )rk   r   r   rO  rm   async_traverserW  rX  s    ```` @r,   async_move_files_to_cachert  F  s^     (3&$ &$P $+67 ,,nl@@   s   AA+$A)%A+c                ^    dfd}t        j                  | |t         j                        S )Nc                    r)| d   j                        r| d   t              d  | d<   nt        j                  | d         r| S  | d    | d<   | S )NrG   )rN  r   rm   r1  )	file_dictprevious_root_urlroot_urls    r,   _add_root_urlz#add_root_url.<locals>._add_root_url  sn    5!1!<!<=N!O(/4E0F0HIIe**9U+;<&Z	%(8'9:	%r/   )rw  rM   )rm   r5  is_file_obj_with_url)ri   ry  rx  rz  s    `` r,   add_root_urlr|    s%       }l6W6WXXr/   c                    |dk(  rd}n|dk(  rd}nt         t        |      }|d   | j                  d   |d<   |d   | j                  d   |d<   t        j                  | ||      S )a  
    Resize and crop an image to fit the specified size.
    args:
        size: `(width, height)` tuple. Pass `None` for either width or height
        to only crop and resize the other.
        crop_type: can be 'top', 'middle' or 'bottom', depending on this
            value, the image will cropped getting the 'top/left', 'middle' or
            'bottom/right' of the image to fit the size.
    raises:
        ValueError: if an invalid `crop_type` is provided.
    top)r   r   center)      ?r  r   rw   )	centering)r   listsizer   fit)r   r  	crop_typer  resizes        r,   resize_and_cropr    st     E	h	$ZFAwHHQKq	AwHHQKq	<<Vv66r/   c                >   	 t        j                  |       }|dk7  s|dk7  r't        |      |z  dz  }t        |      |z  dz  }||| }t        j                  |j                               }	|j                  d	kD  r|	j                  d
|j                        }	|j                   |	fS # t        $ r;}t        |       j	                         }|rd|rdn|  ddz   nd}t        |      |d }~wt        $ r-}t        j                  rt        j                  d      ||d }~ww xY w)NzCannot load audio from file: `ffprobez` not found.zr Please install `ffmpeg` in your system to use non-WAV audio file formats and make sure `ffprobe` is in your PATH.r0  z:Audio format conversion is not supported in the Wasm mode.r   d   rw   rx   )r#   	from_fileFileNotFoundErrorr   is_fileRuntimeErrorOSErrorr   r   WasmUnsupportedErrorr   r   arrayget_array_of_sampleschannelsreshape
frame_rate)
r   crop_mincrop_maxaudioeisfilern  audio_start	audio_endri   s
             r,   audio_from_filer    s1   &&x0" 1}C%j8+c1J)C/	k),88E..01D~~||B/T!!/  	'h'')
  -&Yh,O|\88  	 3Q& 11L s#   B$ $	D-6C##D/(DDc                f   |dk(  rt        |      }n%t        j                  rt        j                  d      t	        |j                         | |j                  j                  t        |j                        dk(  rdn|j                  d         }|j                  ||      }|j                          y )NwavzAAudio formats other than .wav are not supported in the Wasm mode.rw   )r  sample_widthr  r|   )convert_to_16_bit_wavr   r   r  r#   r   dtypeitemsizer   shapeexportclose)r   ri   r   r}   r  r   s         r,   r   r     s    $T*			--O
 	
 ZZ((4::!+!A	E <<<0DJJLr/   c                p   d}| j                   t        j                  t        j                  t        j                  fv rzt        j                  |j                  | j                                | t        j                  |       j                         z  } | dz  } | j                  t        j                        } | S | j                   t        j                  k(  rTt        j                  |j                  | j                                | dz  } | j                  t        j                        } | S | j                   t        j                  k(  r	 | S | j                   t        j                  k(  rTt        j                  |j                  | j                                | dz
  } | j                  t        j                        } | S | j                   t        j                  k(  rWt        j                  |j                  | j                                | dz  dz
  } | j                  t        j                        } | S | j                   t        j                  k(  rTt        j                  |j                  | j                                | dz  } | j                  t        j                        } | S t!        d| j                    d      )	NzCTrying to convert audio automatically from {} to 16-bit int format.i  i   i   i     z2Audio data cannot be converted automatically from z to 16-bit int format.)r  r   float64float32float16warningswarnr}   absmaxastypeint16int32uint16r   int8r   )ri   warnings     r,   r  r    s   SGzzbjj"**bjj99gnnTZZ01bffTl&&((e|{{288$0 K/ 
rxx	gnnTZZ01e|{{288$( K' 
rxx	$ K# 
ryy	 gnnTZZ01e|{{288$ K 
rxx	gnnTZZ01czE!{{288$ K 
rww	gnnTZZ01cz{{288$ K	 @zzl02
 	
r/   c                p   t         dt        j                  dt        dt        j                  dt        j
                  dt        j                  di}t        t        d      r|t           |t        j                  <   t        t        d      r$|t        j                     |t        j                  <   d }dddfd	}t        j                  |       } | j                  }|t        j                  u r|n1|t        u rt        j                  d	      nt        j                  |      }|j                  }	|j                  }
|j                  }|j                  }|j                  }|j                  }t        t        d
      r*t        j                   |	t        j"                  |            }n t        j                   |	|j                        }|r|r| j%                         } | S |dv r>t        j&                  |	      j(                  }t        j&                  |	      j*                  }|dv r>t        j&                  |
      j(                  }t        j&                  |
      j*                  }|dk(  r|  |	||	   d   dz        kD  S |dk(  r)| j-                  |
      }|dk7  r| |
||
   d         z  }|S |dk(  r|dk(  r| j-                  |
      S t        j(                  |       dk  st        j*                  |       dkD  rt/        d       |||	t        j
                  t        j                        }|sr|dk(  rt        j0                  | |      }n#t        j0                  | z
  dz  |      }|dz  }t        j2                  ||       t        j4                  |||       n|dk(  r5t        j0                  | dz   |      }t        j4                  |d||       nQt        j0                  | z
  dz   dz  |      }t        j6                  ||       t        j4                  ||||       |j-                  |
      S |dk(  r |||
t        j
                  t        j                        }|dk(  rt        j0                  | dz  |      } n#t        j8                  | d|      } | dz
  z  z  } t        j                  | |
      S |dk(  r9|dk(  r$ || d|z  d|z  dz
        } | j;                  |
      S  || d|z  d|z        S |dk(  rY || d|z  dz
  d|z        } t        j<                  | j>                  |
      }t        j@                  | d|| j                  d       |S ||kD  r || d|z  dz
  d|z  dz
        S | j-                   d|dz              } | z  }  || d|z  d|z  d      } | z  } | j-                  |
      S ) a  
    Adapted from: https://github.com/scikit-image/scikit-image/blob/main/skimage/util/dtype.py#L510-L531

    Convert an image to the requested data-type.
    Warnings are issued in case of precision loss, or when negative values
    are clipped during conversion to unsigned integer types (sign loss).
    Floating point values are expected to be normalized and will be clipped
    to the range [0.0, 1.0] or [-1.0, 1.0] when converting to unsigned or
    signed integers respectively.
    Numbers are not shifted to the negative side when converting from
    unsigned to signed integer types. Negative values will be clipped when
    converting to unsigned integers.
    Parameters
    ----------
    image : ndarray
        Input image.
    dtype : dtype
        Target data-type.
    force_copy : bool, optional
        Force a copy of the data, irrespective of its current dtype.
    uniform : bool, optional
        Uniformly quantize the floating point range to the integer range.
        By default (uniform=False) floating point values are scaled and
        rounded to the nearest integers, which minimizes back and forth
        conversion errors.
    .. versionchanged :: 0.15
        ``_convert`` no longer warns about possible precision or sign
        information loss. See discussions on these warnings at:
        https://github.com/scikit-image/scikit-image/issues/2602
        https://github.com/scikit-image/scikit-image/issues/543#issuecomment-208202228
        https://github.com/scikit-image/scikit-image/pull/3575
    References
    ----------
    .. [1] DirectX data conversion rules.
           https://msdn.microsoft.com/en-us/library/windows/desktop/dd607323%28v=vs.85%29.aspx
    .. [2] Data Conversions. In "OpenGL ES 2.0 Specification v2.0.25",
           pp 7-8. Khronos Group, 2010.
    .. [3] Proper treatment of pixels as integers. A.W. Paeth.
           In "Graphics Gems I", pp 249-256. Morgan Kaufmann, 1990.
    .. [4] Dirty Pixels. J. Blinn. In "Jim Blinn's corner: Dirty Pixels",
           pp 47-57. Morgan Kaufmann, 1998.
    )FT)rx   rw   float_bool8c                ,     t         fd|D              S )a  Return first of `dtypes` with itemsize greater than `itemsize`
        Parameters
        ----------
        itemsize: int
            The data type object element size.
        Other Parameters
        ----------------
        *dtypes:
            Any Object accepted by `np.dtype` to be converted to a data
            type object
        Returns
        -------
        dtype: data type object
            First of `dtypes` with itemsize greater than `itemsize`.
        c              3  h   K   | ])  }t        j                  |      j                  k\  s&| + y wr'   )r   r  r  )r`  dtr  s     r,   rb  z4_convert.<locals>._dtype_itemsize.<locals>.<genexpr>]  s&     M2288B<+@+@H+LBMs   '22)next)r  dtypess   ` r,   _dtype_itemsizez!_convert.<locals>._dtype_itemsizeM  s      MMMMr/   rw   c                z     t         fd|fdz   D              }t        j                   t        |      z         S )a  Return dtype of `kind` that can store a `bits` wide unsigned int
        Parameters:
        kind: str
            Data type kind.
        bits: int
            Desired number of bits.
        itemsize: int
            The data type object element size.
        Returns
        -------
        dtype: data type object
            Data type of `kind` that can store a `bits` wide unsigned int
        c              3  L   K   | ]  }|d z  k  s|d z  k(  r	dk(  r|  yw)   uNr:   )r`  r   bitskinds     r,   rb  z0_convert.<locals>._dtype_bits.<locals>.<genexpr>n  s4      
q1u~$1q5/dck 
s   !$)      r  )r  r   r  rL   )r  r  r  ss   ``  r,   _dtype_bitsz_convert.<locals>._dtype_bits_  s<      
[9,
 
 xxs1v&&r/   c                p   | j                   j                  }||kD  r.| j                         d|z  k  r| j                   ||            S ||k(  r|r| j	                         S | S ||kD  rb|rSt        j                  | j                   ||            }t        j                  | d||z
  z  || j                   d       |S | d||z
  z  z  } | S ||z  dk(  r|r[t        j                  | j                   ||            }t        j                  | d|z  dz
  d|z  dz
  z  ||j                          |S | j                   ||| j                   j                        d      } | d|z  dz
  d|z  dz
  z  z  } | S ||z  dz   |z  }|rft        j                  | j                   ||            }t        j                  | d|z  dz
  d|z  dz
  z  ||j                          |d||z
  z  z  }|S | j                   ||| j                   j                        d      } | d|z  dz
  d|z  dz
  z  z  } | d||z
  z  z  } | S )	a  Scale an array of unsigned/positive integers from `n` to `m` bits.
        Numbers can be represented exactly only if `m` is a multiple of `n`.
        Parameters
        ----------
        a : ndarray
            Input image array.
        n : int
            Number of bits currently used to encode the values in `a`.
        m : int
            Desired number of bits to encode the values in `out`.
        copy : bool, optional
            If True, allocates and returns new array. Otherwise, modifies
            `a` in place.
        Returns
        -------
        out : array
            Output image array. Has the same kind as `a`.
        r  unsafeoutr  castingr   rw   )r  r  FrP   )r  r  r  r  rP   r   emptyr  floor_dividemultiplyr  )anmrP   r  bor  s          r,   _scalez_convert.<locals>._scalev  s+   & ww||q5QUUWq!t^88Ka011!V#1668**UHHQWWk$&:;1Q<QaggxXaAEl"UaZHHQWWk$&:;A1qadQh7QaggNHH[q!''2B2BC%HPadQhAqD1H-- a!q AHHQWWk$&:;A1qadQh7QaggNaAEl"HH[q!''2B2BC%HPadQhAqD1H--aAEl"r/   r  
obj2sctypeuir  r  r   g      g      ?z.Images of type float must be between -1 and 1.r  )r  r  )r  r   g       @r   r  r  r  Fr  )rw   )T)!boolr   bool_floatr  r  r  hasattrr  r  asarrayr  floatingtyper  r  
issubdtyper  rP   iinfominr  r  r   r  rintclipfloorrM  viewr  r  maximum)imager  r   uniformdtype_ranger  r  dtypeobj_indtypeobj_outdtype_in	dtype_outkind_inkind_outitemsize_initemsize_outis_subdtypeimin_inimax_inimin_outimax_outresultcomputation_type	image_outr  s                          @r,   r   r     sB   X 	m
-w


G


G


GK r8!,U!3BIIr7 +BHH 5BHHN$'.8t JJuE++K BKK 	 E> XXi XXe_  H!!IG  H&&K((L r< mmHbmmE.BCmmHl.?.?@JJLE$((8$((((8$((488I&**88I&** 3xH 5a 81 <=== #~i(s?iI 6q 9::F #~s?<<	**66%=4266%=3#6MNN +(BJJ


 3KKx?OP	KK(A-*	
 Y&	GGI9-GGIxyA_E8a<?OPIGGIq(	:H$s*c1&I
 HHYI.GGIxyA	** 3*BJJ


 c> KKsW}<LME
 FF5#-=>EQ'G+,,Ezz%++ #~s?5!k/1|3Ca3GHE::i(( %[!l2BCC 3ua+o11|3CD%++y1


5!u{{HM \!eQ_q0!l2BQ2FGGLLS,*:;<E	WE5!k/1|+;%HE	XE<<	""r/   c                 R    t         j                  ryt        j                  d      d uS )NFffmpeg)r   r   r   whichr:   r/   r,   ffmpeg_installedr  <  s"    <<!--r/   c                N   ddl m}m} 	 t        |       j                  j                         } |d| di      }|j                  t        j                  t        j                        }t        j                  |d         }|d   d   d   }||fd	v S # |t        t        f$ r Y y
w xY w)zDetermines if a video is playable in the browser.

    A video is playable if it has a playable container and codec.
        .mp4 -> h264
        .webm -> vp9
        .ogg -> theora
    r   )FFprobeFFRuntimeErrorz?-show_format -show_streams -select_streams v -print_format jsonN)global_optionsinputs)stderrstdoutstreams
codec_name)).mp4h264)r	  av1)z.oggtheora).webmvp9)r  vp8)r  r  T)ffmpyr  r  r   suffixr   run
subprocessPIPEjsonloads
IndexErrorKeyError)video_filepathr  r  	containerprobeoutputvideo_codecs          r,   video_is_playabler  D  s     .(//557	\"D)
 *//*//JF1I&Y'*<8;' ,
 
 	
 J1 s   BB B$#B$c                F   ddl m}m} 	 t        j                  d      5 }t        |       j                  d      }t        j                  | |j                          |t        |j                        dit        |      did      }|j                          ddd       t        j                  j                         t              S # 1 sw Y   3xY w# |$ r#}t        d	t        |              | }Y d}~Yd}~ww xY w# t        j                  j                         w xY w)
zLConvert the video to mp4. If something goes wrong return the original video.r   )FFmpegr  F)deleter	  Nz-y -loglevel quiet)r  outputsr  z2Error converting video to browser-playable format )r  r   r  re  NamedTemporaryFiler   with_suffixr   r   r   rL   r  r  r  remove)
video_pathr   r  tmp_fileoutput_pathffr  s          r,   convert_video_to_playable_mp4r*  d  s    ,!((6 		(z*66v>KLLX]]3HMM*D1[)403B
 FFH		 			(-- {!		 		  !B3q6(KL !
 			(-- sA   C A6CC CC C<C72C? 7C<<C? ?!D c                   t         j                  rt        j                  d      t        j                  ddt        |       dddddd	j                  d
      g	      }|j                  d      j                         }t        |      }|S )Nz1Video duration is not supported in the Wasm mode.r  z-iz-show_entrieszformat=durationz-vquietz-ofzcsv={}zp=0r~   )
r   r   r  r  check_outputrL   r}   decodestripr  )r&  durationduration_strduration_floats       r,   get_video_lengthr3  |  s    --?
 	
 &&
OOOE"
	
H ??7+113L<(Nr/   )rr   z
str | dictr5   r\   )rr   rL   r5   rL   )r{   )r}   rL   )   )r   
str | Pathr   intr5   rL   )rG   rL   r5   rL   )r\   r\   )r   rL   r   r6  r5   rL   )r  webp)
r   zImage.Imager   rL   r   rL   r}   rL   r5   rL   )r7  )r   
np.ndarrayr   rL   r}   rL   r5   rL   )
ri   r8  r   r6  r}   rL   r   rL   r5   rL   )ri   r\   r   rL   r   rL   r5   rL   )r   r5  r   rL   r5   rL   )r   rL   r5   r  )r   r6  )rG   rL   r   rL   r5   rL   r'   )r   rL   r   rL   r   
str | Noner5   rL   )r,  zstr | Path | Noner-  rg   r5   r9  )ri   r   )FFF)ri   r   r-  rg   rT  r  )rj   r5  rS  r  )ri   r   r-  rg   rT  r  r5   rM   )ri   zdict | listry  rL   rx  r9  )r  )r   r  )r   rL   r  r  r  r  r5   ztuple[int, np.ndarray])r  )FF)r5   r  )r  rL   r5   r  )r&  rL   r5   rL   )r&  r5  )
__future__r   r   ro   r   r   r  loggingr?  r  r   r  re  r  collections.abcr   r   r   	functoolsr   r	   ior
   pathlibr   typingr   r   r   urllib.parser   r  rR   numpyr   	safehttpxr  gradio_clientr   rm   PILr   r   r   r   gradior   gradio.contextr   gradio.data_classesr   r   r   r   gradio.exceptionsr   r   gradio.route_utilsr   gradio.utilsr   r   r    r!   catch_warningssimplefilterpydubr#   r   pyodide.httprb   r>   SyncByteStreamr%   BaseTransportr<   sync_transportAsyncByteStreamrY   AsyncBaseTransportr_   r	  Clientr  	getLoggerr7   r  gradio.blocksrg   rt   rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r  r  r"  save_url_to_cacher)  r+  r7  rY  rJ  rt  r|  r  r  r   r  r   r  r  r*  r3  r:   r/   r,   <module>rY     s   "        	     : : &   . . !     / > > $ ' P P 5 ) R RX #H(#"# A(<(< A5.. < &'N.U-B-B .u77 0 +,ONOell^4g!#	< ?&
'* O""7+	 		  	
 	 4:B	B #B-0BB
#&03@C(  CL'T0
 ,  CG%(5?8@'@05@@E"  G
GG GT+
b  H
HH H 
HV	Y7B ;>""""27"">"Ne#P	.@0q"# #s   JJ 