
    ;3h                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlmZmZ d dlmZmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZmZ d d
l m!Z!m"Z"m#Z#m$Z$m%Z% d dl&m'Z' d dl(Z(d dl)Z)d dl*m+Z, d dl-Z-d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z= d dl>m?Z?m@Z@mAZAmBZBmCZC d dlDmEZEm+Z+ d dlFmGZGmHZHmIZImJZJ d dlKmLZL d dlMmNZN e!rd dlOmPZPmQZQmRZR d dlSmTZT d dlUmVZV  ej                         ZXdZY G d d      ZZ e/        G d d             Z[ G d de\      Z]dKd Z^	 	 	 	 	 	 	 	 dLd!Z_dMd"Z`	 	 	 	 	 	 dNd#Za	 	 	 	 	 	 	 	 	 	 dOd$ZbdPd%ZcdQd&ZddRd'Ze	 	 	 	 	 	 	 	 dSd(ZfdTd)Zg G d* d+e7      Zh ed,-       G d. d/             Zie G d0 d1             Zj G d2 d3e\      Zk G d4 d5e\      Zl G d6 d7      Zm G d8 d9      ZndUd:ZodVd;ZpdWd<ZqdXd=ZrdYd>ZsdZd?Zt G d@ dA      Zud[dBZvd\dCZwe	 d]	 	 	 	 	 	 	 d^dD       Zxd_dEZyed_dF       Zz	 	 d]	 	 	 	 	 	 	 d`dGZ{ G dH dI      Z|dadbdJZ}y)c    )annotationsN)defaultdictdeque)AsyncGeneratorCallable)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)	dataclass)datetime)Path)NamedTemporaryFile_TemporaryFileWrapper)TYPE_CHECKINGAnyBinaryIOOptionalUnion)urlparse)document)MultipartParserparse_options_header)FormDataHeadersMutableHeaders
UploadFile)MultiPartExceptionMultipartPart)PlainTextResponseResponse)ASGIAppMessageReceiveScopeSend)processing_utilsutils)BlocksConfigDictMediaStreamChunkPredictBodyPredictBodyInternal)Error)SessionState)BlockFunctionBlocksBlocksConfig	EventData)Appz/gradio_apic                  b    e Zd ZdZd Zd Zd Zd ZddZddZ	d	 Z
d
 Zd ZddZddZddZy)Objz
    Using a class to convert dictionaries into objects. Used by the `Request` class.
    Credit: https://www.geeksforgeeks.org/convert-nested-python-dictionary-to-object/
    c                    | j                   j                  |       |j                         D ]3  \  }}t        |t        t
        f      rt        |      }t        | ||       5 y N)__dict__updateitems
isinstancedictlistr5   setattr)selfdict_keyvalues       R/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/route_utils.py__init__zObj.__init__C   sP    U#++- 	&JC%$.E
D#u%	&    c                     | j                   |   S r7   r8   )r?   items     rC   __getitem__zObj.__getitem__J   s    }}T""rE   c                "    || j                   |<   y r7   rG   r?   rH   rB   s      rC   __setitem__zObj.__setitem__M   s    #drE   c              #     K   | j                   j                         D ]+  \  }}t        |t              r|t	        |      f &||f - y wr7   )r8   r:   r;   r5   r<   )r?   rA   rB   s      rC   __iter__zObj.__iter__P   sI     ----/ 	#JC%%DK((El"		#s   A
Ac                    || j                   v ry| j                   j                         D ]  }t        |t              s||v s y y)NTF)r8   valuesr;   r5   rK   s      rC   __contains__zObj.__contains__W   sE    4== ]]))+ 	E%%$%-	 rE   Nc                ,    || v r| j                   |   S |S r7   rG   r?   rH   defaults      rC   getzObj.get_   s    4<==&&rE   c                6    | j                   j                         S r7   )r8   keysr?   s    rC   rW   zObj.keysd   s    }}!!##rE   c                6    | j                   j                         S r7   )r8   rP   rX   s    rC   rP   z
Obj.valuesg   s    }}##%%rE   c                6    | j                   j                         S r7   )r8   r:   rX   s    rC   r:   z	Obj.itemsj   s    }}""$$rE   c                ,    t        | j                        S r7   strr8   rX   s    rC   __str__zObj.__str__m       4==!!rE   c                ,    t        | j                        S r7   r\   rX   s    rC   __repr__zObj.__repr__p   r_   rE   c                D    || v r| j                   j                  |      S |S r7   )r8   poprS   s      rC   rc   zObj.pops   s#    4<==$$T**rE   )returnboolr7   )rd   r]   )__name__
__module____qualname____doc__rD   rI   rL   rN   rQ   rU   rW   rP   r:   r^   ra   rc    rE   rC   r5   r5   =   sC    
&#$#
$&%""rE   r5   c                  H    e Zd ZdZ	 	 	 d	 	 	 	 	 d	dZd Zd
dZddZddZy)Requesta  
    A Gradio request object that can be used to access the request headers, cookies,
    query parameters and other information about the request from within the prediction
    function. The class is a thin wrapper around the fastapi.Request class. Attributes
    of this class include: `headers`, `client`, `query_params`, `session_hash`, and `path_params`. If
    auth is enabled, the `username` attribute can be used to get the logged in user. In some environments,
    the dict-like attributes (e.g. `requests.headers`, `requests.query_params`) of this class are automatically
    converted to dictionaries, so we recommend converting them to dictionaries before accessing
    attributes for consistent behavior in different environments.
    Example:
        import gradio as gr
        def echo(text, request: gr.Request):
            if request:
                print("Request headers dictionary:", dict(request.headers))
                print("Query parameters:", dict(request.query_params))
                print("IP address:", request.client.host)
                print("Gradio session hash:", request.session_hash)
            return text
        io = gr.Interface(echo, "textbox", "textbox").launch()
    Demos: request_ip_headers
    Nc                <    || _         || _        || _        || _        y)at  
        Can be instantiated with either a fastapi.Request or by manually passing in
        attributes (needed for queueing).
        Parameters:
            request: A fastapi.Request
            username: The username of the logged in user (if auth is enabled)
            session_hash: The session hash of the current session. It is unique for each page load.
        N)requestusernamesession_hashkwargs)r?   rn   ro   rp   rq   s        rC   rD   zRequest.__init__   s!       (4&,rE   c                    t        |t              r.t        j                  t        j                  |      t
              S |S )N)object_hook)r;   r<   jsonloadsdumpsr5   )r?   ds     rC   dict_to_objzRequest.dict_to_obj   s*    a::djjm==HrE   c                    | j                   r%| j                  t        | j                   |            S 	 | j                  |   }| j                  |      S # t        $ r}t        d| d      |d }~ww xY w)Nz#'Request' object has no attribute '')rn   rx   getattrrq   KeyErrorAttributeError)r?   nameobjkes       rC   __getattr__zRequest.__getattr__   sy    <<##GDLL$$?@@kk$'
 ##C((	  $9$qAs   A 	A1A,,A1c                L   | j                   j                  t        t        | di             t        t        | di             t        t        | di             t        t        | di             t        | di       xr | j                  j
                  t        | di       xr | j                  j                  dt        | dd      d	       t        | d
      x}r%	 t        j                  |       || j                   d<   d | _        | j                  S # t        j                  $ r Y (w xY w)Nheadersquery_paramscookiespath_paramsclient)hostporturl )r   r   r   r   r   r   staterequest_state)rq   r9   r<   r{   r   r   r   hasattrpicklerv   PicklingErrorrn   r8   )r?   r   s     rC   __getstate__zRequest.__getstate__   s   i <= $WT>2%F Gi <=#GD-$DE#D(B7LDKK<L<L#D(B7LDKK<L<L tUB/
	
 $D'22=2]+/<O, }} '' s   $D D#"D#c                H    |j                  dd       x}r|| _        || _        y )Nr   )rc   r   r8   )r?   r   r   s      rC   __setstate__zRequest.__setstate__   s&    !IIot<<=<&DJrE   )NNN)rn   zfastapi.Request | Nonero   
str | Nonerp   r   )r~   r]   )rd   dict[str, Any])r   r   )	rf   rg   rh   ri   rD   rx   r   r   r   rj   rE   rC   rl   rl   y   sG    0 +/##'	-'- - !	-*
).rE   rl   c                      e Zd Zy)FnIndexInferErrorNrf   rg   rh   rj   rE   rC   r   r          rE   r   c                8   |j                   r0| j                  |j                      }|j                  j                  }n| j                  }|j                  8|(|j                         D ]  }|j                  |k(  s|c S  t        d|       ||j                     S )Nz-Could not infer function index for API name: )rp   state_holderblocks_configfnsfn_indexrP   api_namer   )blocksr   bodysession_stater   fns         rC   get_fnr      s    ++D,=,=>))--jj}}jjl ;;(*I  ;H:F
 	
 4==!!rE   c                $   |j                   r| j                  g| _        | j                  r@| j                  rt        ||      g}|S t        || j                  | j                        }|S |t        d      t        ||| j                        }|S )N)ro   rn   )ro   rn   rp   z0request must be provided if body.request is None)cancelsrp   datarn   batchedrl   
ValueError)r   r   ro   rn   
gr_requests        rC   compile_gr_requestr      s     
zz&&'	||<<!8WEFJ  !!4<<dFWFWJ  ?OPPwT=N=N

 rE   c                @   |j                   }t        |dd       }|e| j                  |   }|d }||fS || j                  v r!d }| j                  j	                  |       ||fS | j
                  j                  |      }||fS t        | j                               }d }||fS )Nrp   )	event_idr{   r   iterators_to_resetremove	iteratorsrU   r-   
get_blocks)appr   r   rp   r   iterators         rC   restore_session_stater     s    }}H46L((6 H ("" ///H""))(3 ("" }}((2H
 ("" %S^^%56(""rE   c                    ddl m} |j                  } ||r| j                  j	                  |      nd |j
                        }|S )Nr   r1   )gradio.helpersr2   
trigger_idr   rU   
event_data)r   r   r2   targetr   s        rC   prepare_event_datar     sA     )__F,2  (J rE   c                R  K   t        | |      \  }}t        |j                  |      }|j                  }t	        |dd       }	|j
                  }
|j                   xr |j                  }|r|
g}
	 t        j                         5  | j                         j                  ||
||||	||d|j                  |       d {   }d d d        j                  dd       }||| j                  |<   t        |t               r|	 |r|d   d   |d<   |S 7 Q# 1 sw Y   PxY w# t"        $ r || j                  j%                  |      nd }|]t'        |      }| j                         j(                  |	   j%                  |i       }|j+                         D ]  }|j-                            w xY ww)N)r   r   rp   T)block_fninputsrn   r   r   rp   r   r   in_event_listenersimple_format	root_pathr   r   r   )r   r   r   r   r{   r   r   batchr'   MatplotlibBackendManangerr   process_apir   rc   r   r;   r,   BaseExceptionrU   idpending_streamsrP   
end_stream)r   r   r   r   r   r   r   r   r   rp   r   batch_in_single_outoutputrun_idr   streams                   rC   call_process_apir   -  s     4$GM8#M$?$?FJ}}H46LYYF"ll*7rxx,,. 	>>+77"#!)!%"&"00# 8  F	 ::j$/&.CMM(#fe$L % *vM?	 	&  	2:2F3==$$X.D\F 00>BB62N  *002 $!!#$	sI   A,F'/D 8D;D<D =D =F'DDD B	F$$F'c                    | j                   j                  |      }|r"|j                  d      d   j                         S y )N,r   )r   rU   splitstrip)rn   header_nameheader_values      rC   get_first_header_valuer   d  s;    ??&&{3L!!#&q)//11rE   c                   t        | d      }|rd| nt        | j                        }t        j                  |      }|j                  d      }t        |      j                  d      }t        | d      dk(  r|j                  dd      }|j                  d      }t        |      d	kD  r|s|dt        |        }|j                  d      }t        j                  |      }|S )
a`  
    Examines the request headers to determine the origin of the request.
    If the request includes the x-forwarded-host header, it is used directly to determine the origin.
    Otherwise, the request url is used and the route path is stripped off.

    The returned URL is a httpx.URL object without a trailing slash, e.g. "https://example.com"
    zx-forwarded-hosthttp://N)query/zx-forwarded-protohttpszhttps://r   )	r   r]   r   httpxURL	copy_withrstripreplacelen)rn   
route_pathx_forwarded_hostroot_urls       rC   get_request_originr   k  s     .g7IJ/?)*+SEUHyy"H!!!-H8}##C(Hg':;wF##Iz:""3'J
:#3.s:./s#Hyy"HOrE   c                "   t          d}t          d}| j                  j                  j                  d      }|j	                  |      r|S |j                  |      }|dk\  r||t        |       S t        dt        | j                         d      )a  
    Extracts the API call path from the request URL.

    If the URL (without query parameters) ends with "{API_PREFIX}/queue/join", that exact path is returned.
    Otherwise, if the URL contains "{API_PREFIX}/call", the substring starting from "{API_PREFIX}/call" is returned.
    This allows for dynamic API calls to methods other than "predict".

    Raises:
        ValueError: If the request URL does not match any recognized API call pattern.
    z/queue/joinz/callr   r   zRequest url 'z"' has an unknown api call pattern.)	
API_PREFIXr   pathr   endswithrfindr   r   r]   )rn   queue_api_urlgeneric_api_urlrequest_pathstart_indexs        rC   get_api_call_pathr     s     "l+.M#E*O;;##**3/L]+$$_5KaK#l*;<<

GKK())KL rE   c                    |r&t        j                  |      r|j                  d      S t        | |      }|r!|j                  |k7  r|j                  |      }t        |      j                  d      S )a  
    Gets the root url of the Gradio app (i.e. the public url of the app) without a trailing slash.

    This is how the root_url is resolved:
    1. If a user provides a `root_path` manually that is a full URL, it is returned directly.
    2. If the request has an x-forwarded-host header (e.g. because it is behind a proxy), the root url is
    constructed from the x-forwarded-host header. In this case, `route_path` is not used to construct the root url.
    3. Otherwise, the root url is constructed from the request url. The query parameters and `route_path` are stripped off.
    And if a relative `root_path` is provided, and it is not already the subpath of the URL, it is appended to the root url.

    In cases (2) and (3), We also check to see if the x-forwarded-proto header is present, and if so, convert the root url to https.
    And if there are multiple hosts in the x-forwarded-host or multiple protocols in the x-forwarded-proto, the first one is used.
    r   )r   )client_utilsis_http_url_liker   r   r   r   r]   )rn   r   r   r   s       rC   get_root_urlr     sg    " \229=$$!':6HX]]i/%%9%5x=$$rE   c                r    	 | j                  |      S # t        t        f$ r | j                  d      cY S w xY w)Nlatin-1)decodeUnicodeDecodeErrorLookupError)srccodecs     rC   _user_safe_decoder     s9    %zz%  , %zz)$$%s     66c                  @     e Zd ZdZdddd	 	 	 	 	 	 	 	 	 d fdZ xZS )GradioUploadFilez UploadFile with a sha attribute.Nsizefilenamer   c                   t         |   ||||       t        j                         | _        | j                  j                  t        j                         y )Nr   )superrD   hashlibsha256shar9   r&   	hash_seed)r?   filer   r   r   	__class__s        rC   rD   zGradioUploadFile.__init__  s@     	D8WM>>#(223rE   )
r  r   r   
int | Noner   r   r   zHeaders | Nonerd   None)rf   rg   rh   ri   rD   __classcell__)r  s   @rC   r   r     sK    *  #"&
4
4 	
4
 
4  
4 

4 
4rE   r   T)frozenc                  "    e Zd ZU ded<   ded<   y)FileUploadProgressUnitr]   r   int
chunk_sizeNrf   rg   rh   __annotations__rj   rE   rC   r  r    s    MOrE   r  c                  "    e Zd ZU ded<   ded<   y)FileUploadProgressTrackerzdeque[FileUploadProgressUnit]r   re   is_doneNr  rj   rE   rC   r  r    s    ((MrE   r  c                      e Zd Zy)!FileUploadProgressNotTrackedErrorNr   rj   rE   rC   r  r    r   rE   r  c                      e Zd Zy) FileUploadProgressNotQueuedErrorNr   rj   rE   rC   r  r    r   rE   r  c                  L    e Zd Zd
dZddZddZddZddZddZddZ	ddZ
y	)FileUploadProgressc                N    i | _         t        t        j                        | _        y r7   )	_statusesr   asyncioEvent_signalsrX   s    rC   rD   zFileUploadProgress.__init__  s    ?A#GMM2rE   c                    || j                   vr?t        t               d      | j                   |<   | j                  |   j	                          y y )NF)r  r  r   r  setr?   	upload_ids     rC   trackzFileUploadProgress.track  s?    DNN*(A%'5(QDNN9%MM)$((* +rE   c                X   K   | j                   |   j                          d {   S 7 wr7   )r  waitr   s     rC   
is_trackedzFileUploadProgress.is_tracked  s$     ]]9-224444s   !*(*c           	        || j                   vr| j                  |       | j                   |   j                  }t        |      dk(  r%|j	                  t        |t        |                   y |j                         }|j                  |k7  r%|j	                  t        |t        |                   y |j	                  t        ||j                  t        |      z                y )Nr   )	r  r"  r   r   appendr  popleftr   r  )r?   r!  r   message_bytesqueue	last_units         rC   r'  zFileUploadProgress.append  s    DNN*JJy!y)//u:?LL/#m:LMNI!!X-3Hc->PQR* !,,s=/AArE   c                j    || j                   vr| j                  |       d| j                   |   _        y NT)r  r"  r  r   s     rC   set_donezFileUploadProgress.set_done  s+    DNN*JJy!,0y!)rE   c                d    || j                   vr
t               | j                   |   j                  S r7   )r  r  r  r   s     rC   r  zFileUploadProgress.is_done
  s,    DNN*355~~i(000rE   c                <    || j                   v r| j                   |= y y r7   )r  r   s     rC   stop_trackingz FileUploadProgress.stop_tracking  s    &y) 'rE   c                    || j                   vr
t               	 | j                   |   j                  j                         S # t        $ r}t               |d }~ww xY wr7   )r  r  r   rc   
IndexErrorr  )r?   r!  es      rC   rc   zFileUploadProgress.pop  sU    DNN*355	<>>),226688 	<24!;	<s   &A 	A
AANrd   r  )r!  r]   )r!  r]   rd   re   )r!  r]   r   r]   r)  bytes)r!  r]   rd   r  )rf   rg   rh   rD   r"  r%  r'  r.  r  r1  rc   rj   rE   rC   r  r    s*    3+
5&1
1
*<rE   r  c                      e Zd ZdZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZddZdd	Zdd
Z	ddZ
ddZddZddZddZy)GradioMultiPartParsera  Vendored from starlette.MultipartParser.

    Thanks starlette!

    Made the following modifications
        - Use GradioUploadFile instead of UploadFile
        - Use NamedTemporaryFile instead of SpooledTemporaryFile
        - Compute hash of data as the request is streamed

    i   i  N)	max_files
max_fieldsr!  upload_progressc                  || _         || _        || _        || _        g | _        || _        || _        d| _        d| _        || _	        d| _
        d| _        t               | _        d| _        g | _        g | _        g | _        y )Nr   rE   r   )r   r   r9  r:  r:   r!  r;  _current_files_current_fieldsmax_file_size_current_partial_header_name_current_partial_header_valuer   _current_part_charset_file_parts_to_write_file_parts_to_finish_files_to_close_on_error)r?   r   r   r9  r:  r!  r;  r?  s           rC   rD   zGradioMultiPartParser.__init__*  s     "$?A
". *36)47**_GI!:<"EG%rE   c                "    t               | _        y r7   )r   rB  rX   s    rC   on_part_beginz#GradioMultiPartParser.on_part_beginG  s    *_rE   c                j   ||| }| j                   E| j                   j                  | j                  | j                  j                  j
                  |       | j                  j                   | j                  xj                  |z  c_        y | j                  j                  | j                  |f       y r7   )r;  r'  r!  rB  r  r   r   rD  )r?   r   startendr)  s        rC   on_part_dataz"GradioMultiPartParser.on_part_dataJ  s    U3+  ''""''00
 ""*##}4#%%,,d.@.@--PQrE   c           	        | j                   j                  c| j                  j                  | j                   j                  t        | j                   j                  t        | j                              f       y | j                  j                  | j                          | j                  j                  | j                   j                  | j                   j                  f       y r7   )
rB  r  r:   r'  
field_namer   r   r]   rC  rE  rX   s    rC   on_part_endz!GradioMultiPartParser.on_part_endW  s    ""*JJ&&11%d&8&8&=&=s4==?QR &&--d.@.@A JJt11<<d>P>P>U>UVWrE   c                4    | xj                   ||| z  c_         y r7   )r@  r?   r   rJ  rK  s       rC   on_header_fieldz%GradioMultiPartParser.on_header_fieldf  s    ))T%_<)rE   c                4    | xj                   ||| z  c_         y r7   )rA  rQ  s       rC   on_header_valuez%GradioMultiPartParser.on_header_valuei  s    **d5o=*rE   c                    | j                   j                         }|dk(  r| j                  | j                  _        | j                  j
                  j                  || j                  f       d| _         d| _        y )Ns   content-dispositionrE   )r@  lowerrA  rB  content_dispositionitem_headersr'  )r?   fields     rC   on_header_endz#GradioMultiPartParser.on_header_endl  sm    11779**595W5WD2''..D667	
 -0)-0*rE   c                @   t        | j                  j                  xs d      \  }}	 t        |d   t	        | j
                              | j                  _        d|v r| xj                  dz  c_	        | j                  | j                  kD  rt        d| j                   d      t        |d   t	        | j
                              }t        d	      }| j                  j                  |       t        |d
|t        | j                  j                               | j                  _        y | xj$                  dz  c_        | j$                  | j&                  kD  rt        d| j&                   d      d | j                  _        y # t        $ r}t        d      |d }~ww xY w)NrE   s   namez=The Content-Disposition header field "name" must be provided.s   filename   z+Too many files. Maximum number of files is .F)deleter   )raw)r  r   r   r   z-Too many fields. Maximum number of fields is )r   rB  rW  r   r]   rC  rN  r|   r   r=  r9  r   rF  r'  r   r   rX  r  r>  r:  )r?   _optionsr4  r   tempfiles         rC   on_headers_finishedz)GradioMultiPartParser.on_headers_finishedv  s|   )$*<*<*P*P*WTWX
7	,= #dmm"4-D) '!1$""T^^3(A$..AQQRS  ))=s4==?QRH)7H))00:&6!D$6$6$C$CD	'D#   A% ##doo5(CDOOCTTUV  '+D#3  	$O	s   1F 	FFFc                     y r7   rj   rX   s    rC   on_endzGradioMultiPartParser.on_end  s    rE   c           	     p  K   t        | j                  d         \  }}|j                  dd      }t        |t              r|j                  d      }|| _        	 |d   }| j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                   d}t#        ||      }	 | j$                  2 3 d {   }|j'                  |       | j(                  D ]  \  }	}
|	j*                  sJ |	j*                  j'                  |
       d {    |	j*                  j,                  j/                  |
       t1        j2                  |	j*                  j*                  j4                        j6                  | j8                  kD  s| j:                  %| j:                  j=                  | j>                         t        d| j8                   d	       | j@                  D ]3  }	|	j*                  sJ |	j*                  jC                  d
       d {    5 | j(                  jE                          | j@                  jE                          # t        $ r}t        d      |d }~ww xY w7 7 X7 _6 nW# t        $ rK}| jF                  D ]5  }|jI                          tK        |j4                        jM                          7 |d }~ww xY w|jO                          | j:                  %| j:                  j=                  | j>                         tQ        | jR                        S w)NzContent-Types   charsetzutf-8r   s   boundaryzMissing boundary in multipart.)rH  rL  rO  rR  rT  rZ  rc  re  z+File size exceeded maximum allowed size of z bytes.r   )*r   r   rU   r;   r6  r   rC  r|   r   rH  rL  rO  rR  rT  rZ  rc  re  r   r   writerD  r  r  r9   osstatr~   st_sizer?  r;  r.  r!  rE  seekclearrF  closer   unlinkfinalizer   r:   )r?   r`  paramscharsetboundaryr4  	callbacksparserchunkpartr   excr  s                rC   parsezGradioMultiPartParser.parse  s    (n)EF	6**Z1gu%nnY/G	Nk*H "// --++#33#33!//#'#;#;kk	
	 !95	#{{ 3 3eU# #'";"; 	JD$99$9))//$///IIMM((.wwtyy~~223;;d>P>PP//; 0099$..I0I$J\J\I]]de 	 !66 ,D99$9))..+++, ))//1**002Q  	N$%EFAM	N&3 0 ,'  +, " 	55 )

TYY&&() I	 	+  ))$..9

##s   AL6I" A'L6J	 JI?JAJ	 *J+A3J	 BJ	 %J&<J	 "	I<+I77I<<L6?JJ	 J	 J	 L6		KAKKAL6)r   r   r   zAsyncGenerator[bytes, None]r9  Union[int, float]r:  ry  r!  r   r;  zFileUploadProgress | Noner?  zint | floatrd   r  r5  )r   r6  rJ  r  rK  r  rd   r  )rd   r   )rf   rg   rh   ri   r?  rD   rH  rL  rO  rR  rT  rZ  rc  re  rx  rj   rE   rC   r8  r8    s    	  M (,(, $59HH ,H
 %H &H H 3H #H 
H:-RX=>1+B<$rE   r8  c                \    t        | |d      D ]  \  }}t        j                  ||        y )NF)strict)zipshutilmove)filesdestinationsr  dests       rC   move_uploaded_files_to_cacher    s,    %e<  
dD$ rE   c                n    | j                  d      }|||k7  r|| d<   t        j                  | ||      } | S )z
    Updates the root "key" in the config dictionary to the new root url. If the
    root url has changed, all of the urls in the config that correspond to component
    file urls are updated to use the new root url.
    root)rU   r&   add_root_url)configr  previous_roots      rC   update_root_in_configr    sA     JJv&M 5v!..vt]KMrE   c                :    dd}t        j                  | |d       S )zS
    Updates the example values in the api_info dictionary to use a public url
    c                    | j                  d      }|:t        j                  |      r%t        j                  |d         r| S | d   d   |d<   | S )Nparameter_defaultr   example_input)rU   r   is_file_obj_with_urlr   )	file_dictdefault_values     rC   _add_root_urlz>update_example_values_to_use_public_url.<locals>._add_root_url  s^    !&9:$)J)J*
 ,,]5-AB   $-_#=e#DM% rE   c                .    t        | t              xr d| v S )Nr  )r;   r<   )rw   s    rC   <lambda>z9update_example_values_to_use_public_url.<locals>.<lambda>   s    *Q%B*=*B rE   )r  r<   )r   traverse)api_infor  s     rC   'update_example_values_to_use_public_urlr    s%    
   B rE   c                f    t        j                  | j                         |j                               S r7   )hmaccompare_digestencode)input_passwordcorrect_passwords     rC   compare_passwords_securelyr    s(    ~4468H8O8O8QRRrE   c                6    d}t        j                  ||       duS )zThis regex matches strings that start with a scheme (one or more characters not including colon, slash, or space)
    followed by ://, or start with just //, \/, /\, or \ as they are interpreted as SMB paths on Windows.
    z0^(?:[a-zA-Z][a-zA-Z0-9+\-.]*://|//|\\\\|\\/|/\\)N)rematch)stringpatterns     rC   starts_with_protocolr    s      BG88GV$D00rE   c                l    | syd| vrd| z   } 	 t        |       j                  xs dS # t        $ r Y yw xY w)a  
    Returns the hostname of a given url, or an empty string if the url cannot be parsed.
    Examples:
        get_hostname("https://www.gradio.app") -> "www.gradio.app"
        get_hostname("localhost:7860") -> "localhost"
        get_hostname("127.0.0.1") -> "127.0.0.1"
    r   z://r   )r   hostname	Exception)r   s    rC   get_hostnamer    sG     C#o}%%++ s   ' 	33c                      e Zd Z	 d		 	 	 	 	 d
dZddZddZ	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZddZe	dd       Z
y)CustomCORSMiddlewarec                   || _         d| _        dj                  | j                        t        d      dd| _        ddi| _        g d| _        |rt        j                  d      | j                  j                  d	       y y )
N)DELETEGETHEADOPTIONSPATCHPOSTPUTz, iX  true)zAccess-Control-Allow-MethodszAccess-Control-Max-Age Access-Control-Allow-Credentialsr  )	localhostz	127.0.0.1z0.0.0.0GRADIO_LOCAL_DEV_MODEnull)
r   all_methodsjoinr]   preflight_headerssimple_headerslocalhost_aliasesrh  getenvr'  )r?   r   strict_corss      rC   rD   zCustomCORSMiddleware.__init__&  s    
 W,0IId6F6F,G&)#h06"

  B6J!Fbii(?@L ""))&1	 MrE   c                v  K   |d   dk7  r| j                  |||       d {    y t        |      }|j                  d      }|| j                  |||       d {    y |d   dk(  r)d|v r%| j                  |      } ||||       d {    y | j	                  ||||       d {    y 7 7 V7 '7 w)	Ntypehttpscopeoriginmethodr  zaccess-control-request-method)request_headers)r   r   rU   preflight_responsesimple_response)r?   r  receivesendr   r  responses          rC   __call__zCustomCORSMiddleware.__call__;  s     =F"((5'4000&X&>((5'4000?i',Kw,V..w.GH5'4000""5'4"QQQ 1
 1 1QsE   B9B1:B9B30B9B5B9+B7,B93B95B97B9c                    t        | j                        }|d   }| j                  |      r||d<   |j                  d      }|||d<   t	        dd|      S )NOriginAccess-Control-Allow-Originzaccess-control-request-headerszAccess-Control-Allow-HeadersOK   )status_coder   )r<   r  is_valid_originrU   r   )r?   r  r   r  requested_headerss        rC   r  z'CustomCORSMiddleware.preflight_responseJ  sg    t--. *05;G12+//0PQ(6GG23 3HHrE   c                   K   t        j                  | j                  ||      }| j                  |||       d {    y 7 w)N)r  r  )	functoolspartial_sendr   )r?   r  r  r  r  s        rC   r  z$CustomCORSMiddleware.simple_responseT  s6        $Xhhugt,,,s   9AAAc                (  K   |d   dk7  r ||       d {    y |j                  dg        t        |      }|j                  | j                         |d   }| j	                  |      r| j                  ||        ||       d {    y 7 w7 w)Nr  zhttp.response.startr   r  r  )
setdefaultr   r9   r  r  allow_explicit_origin)r?   messager  r  r   r  s         rC   r  zCustomCORSMiddleware._sendZ  s      6?33w-9b) w/t**+ *0&&w77m   	s"   BBA1BB	BBc                ~    |d   }|d   }t        |      }t        |      }|| j                  vxs || j                  v S )Nr  Host)r  r  )r?   r  r  r   	host_nameorigin_names         rC   r  z$CustomCORSMiddleware.is_valid_originh  sR     *v& &	"6* T333 5d444	
rE   c                0    || d<   | j                  d       y )Nr  r  )add_vary_header)r   r  s     rC   r  z*CustomCORSMiddleware.allow_explicit_origins  s    17-.)rE   N)T)r   r!   r  re   rd   r  )r  r$   r  r#   r  r%   rd   r  )r  r   rd   r    )
r  r$   r  r#   r  r%   r  r   rd   r  )r  r"   r  r%   r  r   rd   r  )r  r   rd   re   )r   r   r  r]   rd   r  )rf   rg   rh   rD   r  r  r  r  r  staticmethodr  rj   rE   rC   r  r  "  s     !22 2 
	2*RI--%,-48-KR-	-&*=D		
 * *rE   r  c           	        t               }| j                  j                         D ]&  }|j                  t	        |dt                            ( | j
                  D ]  }t               }|D ]  }||v r	 t        |      }t        j                  |j                         j                        }|$t        j                         |z
  j                  |kD  r&t        j                  |       |j                  |        ||z  } y# t         $ r Y w xY w)zGDelete files that are older than age. If age is None, delete all files.keep_in_cacheN)r  r   rP   r9   r{   temp_file_setsr   r   fromtimestamplstatst_ctimenowsecondsrh  r   addFileNotFoundError)	r   agedont_delete	componenttemp_set	to_remover  	file_pathmodified_times	            rC   delete_files_created_by_appr  y  s    %K]]))+ G	79osuEFG))  E	 
	D{" J	 ( 6 6y7H7Q7Q R;8<<>M#A"J"JS"PIIdOMM$'
	 	I % s   2BD  	DDc                   K   	 t        j                  |       d{    t        j                  j	                  t
        | j                         |       d{    Y7 @7 w)zVStartup task to delete files created by the app based on time since last modification.N)r  sleepanyio	to_threadrun_syncr  r   r   	frequencyr  s      rC   delete_files_on_scheduler    sS     
mmI&&&oo&&')93
 	
 	
 &	
s!   A!A:A!AA!A!c                  K   t        j                  t        | ||             d t        | j	                         d       yw)zKA context manager that triggers the startup and shutdown events of the app.N)r  )r  create_taskr  r  r   r  s      rC   _lifespan_handlerr    s4     
 0iEF	 0d;s   AAc                   K   	 | j                   j                          t        j                  d       d{    87 w)z&Delete all expired state every second.r\  N)r   delete_all_expired_stater  r  r   s    rC   _delete_stater    s5     
113mmA s   4><>c               R   K   t        j                  t        |              d yw)z9When the server launches, regularly delete expired state.N)r  r  r  r  s    rC   _delete_state_handlerr    s      c*+	s   %'c                .     t         d fd       }|S )zWReturn a context manager that applies _lifespan_handler and user_lifespan if it exists.c               r  K   t               4 d {   }|j                  t        |              d {    r&r$|j                  t        |              d {    |j                   |              d {    d  d d d       d {    y 7 7 e7 ?7  7 # 1 d {  7  sw Y   y xY wwr7   )r	   enter_async_contextr  r  )r   stackr  r  user_lifespans     rC   _handlerz)create_lifespan_handler.<locals>._handler  s     !# 	 	u++,A#,FGGGS//0A#yRU0VWWW(//c0BCCC	 	 	GWC	 	 	 	sx   B7BB7B"B'B"B B"=B>	B"B7B B7B"B"B" B7"B4(B+)B40B7r   r3   )r
   )r	  r  r  r
  s   ``` rC   create_lifespan_handlerr    s       OrE   c                  $    e Zd ZdddZddZd Zy)MediaStreamNc                f    g | _         d | _        d| _        d| _        d| _        d| _        || _        y )NFr   ze#EXTM3U
#EXT-X-PLAYLIST-TYPE:EVENT
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:0
   )segmentscombined_fileendedsegment_indexplaylistmax_durationdesired_output_format)r?   r  s     rC   rD   zMediaStream.__init__  s:    02)-
 E%:"rE   c                   K   |sy t        t        j                               }| j                  j	                  d|i|       t        | j                  |d         dz   | _        y w)Nr   durationr\  )r]   uuiduuid4r  r'  maxr  )r?   r   
segment_ids      rC   add_segmentzMediaStream.add_segment  sW     &
dJ7$78 1 14
3CDqHs   A"A$c                    d| _         y r-  )r  rX   s    rC   r   zMediaStream.end_stream  s	    
rE   r7   )r  r   )r   zMediaStreamChunk | None)rf   rg   rh   rD   r  r   rj   rE   rC   r  r    s    ;IrE   r  c                    ddl }t        j                  | |d      }|j                  |j	                               j                         j                  d      }|S )zSCreate a URL-safe short hash of the data. Used to generate unique short deep links.r   NF)digest_sizeusedforsecurity=)base64r   blake2burlsafe_b64encodedigestr   r   )r   r!  r$  hash_objurl_safe_hashs        rC   create_url_safe_hashr*    sI    teTH,,X__->?FFHOOPSTMrE   )r   r/   r   r   r   r*   rd   r.   )r   r+   r   r.   ro   zOptional[str]rn   zOptional[fastapi.Request])r   r3   r   r+   )r   r0   r   r+   rd   r2   )
r   r3   r   r+   r   zUnion[Request, list[Request]]r   r.   r   r]   )rn   fastapi.Requestr   r]   )rn   r+  r   r]   rd   z	httpx.URL)rn   r+  rd   r]   )rn   r+  r   r]   r   r   rd   r]   )r   r6  r   r]   rd   r]   )r  	list[str]r  r,  rd   r  )r  r(   r  r]   rd   r(   )r  r   rd   r   )r  r]   r  r]   rd   re   )r  r]   rd   re   )r   r]   rd   r]   )r   r/   r  r  rd   r  )r   r3   r  r  r  r  rd   r  )r\  r\  )r   r3   r  r  r  r  rd   r   r  )r	  z3Callable[[App], AbstractAsyncContextManager] | Noner  r  r  r  rd   z,Callable[[App], AbstractAsyncContextManager])   )r   r6  )~
__future__r   r  r  r   r  rt   rh  r   r  r}  	threadingr  collectionsr   r   collections.abcr   r   
contextlibr   r	   r
   dataclassesr   python_dataclassr   pathlibr   rb  r   r   typingr   r   r   r   r   urllib.parser   r  fastapigradio_client.utilsr'   r   r   gradio_client.documentationr   python_multipart.multipartr   r   starlette.datastructuresr   r   r   r   starlette.formparsersr   r   starlette.responsesr   r    starlette.typesr!   r"   r#   r$   r%   gradior&   gradio.data_classesr(   r)   r*   r+   gradio.exceptionsr,   gradio.state_holderr-   gradio.blocksr.   r/   r0   r   r2   gradio.routesr3   Lockconfig_lockr   r5   rl   r  r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r8  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r*  rj   rE   rC   <module>rH     s   "      	  	    * 4 W W 5   >  "   *  0 L R R C ; B B *  $ ,AA(! inn
9 9x 
X X Xv		 	"&
  '	6#0
 4	4
4 .4 		4
 4n06%%*-%:D%%8%4z 4    
   
		 		y 	4< 4<nz$ z$z 

2S1$T* T*n.
 -.<	<<'*<< < 
 
 F 
 2	( ,rE   