a
    d                  	   @  sJ  d Z ddlmZ ddlZddlZejdkr8ddlmZ n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mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZ ddl m!Z! 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(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZC ddlDZDddlEmFZF ddlDmGZGmHZH ddlImJZJ ddlKmLZLmMZM ddlNmOZO ddlPmQZQ ddlRmSZS ddlTmUZUmVZV ddlWmXZXmYZYmZZZ e[  ed\d] Z^ed\dd d!] Z_ed\dd d"] Z`ed\d#a ZbG d$d% d%e2Zcd&d' Zde7e^d(Zeedeejfjgd'< e#h ZiG d)d* d*e'Zjd+d+d+d,d-d.Zkd/d0d1d2Zld+d3d4d5Zme:d6 G d7d8 d8Zne9 G d9d: d:Zoe9 dBd;d<d+d=d>d;d?d@dAZpdS )CzImplements a FastAPI server to run the gradio interface. Note that some types in this
module use the Optional/Union notation so that they work correctly with pydantic.    )annotationsN)   	   files)TimeoutError)defaultdict)deepcopy)Path)AnyDictListOptionalType)urlparse)DependsFastAPIFileHTTPException
UploadFile	WebSocketstatus)CORSMiddleware)FileResponseHTMLResponseJSONResponsePlainTextResponse)OAuth2PasswordRequestForm)Jinja2Templates)documentset_documentation_group)TemplateNotFound)BackgroundTask)RedirectResponseStreamingResponse)WebSocketState)utils
wasm_utils)Context)PredictBody	ResetBody)Error)	EventData)attach_oauth)
EstimationEvent)cancel_tasksrun_coro_in_backgroundset_task_namegradio	templatesZfrontendZstaticZassetszversion.txtc                   @  sH   e Zd ZdZedddddZdddddZedd	dd
dZdS )ORJSONResponsezapplication/jsonr   bytes)contentreturnc                 C  s   t j| t jt jB tdS )N)optiondefault)orjsondumpsZOPT_SERIALIZE_NUMPYZOPT_PASSTHROUGH_DATETIMEstrr7    r?   V/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/routes.py_renderG   s
    
zORJSONResponse._renderc                 C  s
   t |S N)r5   rA   )selfr7   r?   r?   r@   renderO   s    zORJSONResponse.renderr=   c                 C  s   t | dS )Nzutf-8)r5   rA   decoder>   r?   r?   r@   _render_strR   s    zORJSONResponse._render_strN)__name__
__module____qualname__
media_typestaticmethodrA   rD   rF   r?   r?   r?   r@   r5   D   s   r5   c                 C  s0   t t| ddddddddS )	N<z\u003c>z\u003e&z\u0026'z\u0027)
markupsafeZMarkupr5   rF   replace)valuer?   r?   r@   toorjsonW   s    
rS   )	directoryc                      s^   e Zd ZdZ fddZdddddZdd	d
dZdd Zedddd dddZ	  Z
S )Appz
    FastAPI App Wrapper
    c                   s   i | _ d | _d | _i | _tt| _tt| _t	
 | _td| _d| _tjdpfttt d | _|dd  |dd  t jf i | d S )N    FZGRADIO_TEMP_DIRr3   Zdocs_urlZ	redoc_url)tokensauthblocksstate_holderr   dict	iteratorssetiterators_to_resetasyncioLocklocksecretstoken_urlsafequeue_tokenstartup_events_triggeredosenvirongetr=   r
   tempfile
gettempdiruploaded_file_dir
setdefaultsuper__init__)rC   kwargs	__class__r?   r@   rn   l   s    


zApp.__init__gradio.BlocksNone)rY   r8   c                 C  s|   |j }|d ur0t|s(dd |D | _ q6|| _ nd | _ || _t| jdrX| jj| j t | _	|j
| _
i | _|j| _d S )Nc                 S  s   i | ]}|d  |d qS )r      r?   ).0accountr?   r?   r@   
<dictcomp>       z%App.configure_app.<locals>.<dictcomp>_queue)rX   callablerY   hasattrry   Zset_access_tokenrd   rf   getcwdcwdfavicon_pathrW   	root_path)rC   rY   rX   r?   r?   r@   configure_app   s    
zApp.configure_appr8   c                 C  s   | j d u rtd| j S )Nz+No Blocks has been configured for this app.)rY   
ValueErrorrC   r?   r?   r@   
get_blocks   s    
zApp.get_blocksc                   s|   t | | jsJ t fdd| jjD }|s:td jd}i }tj	d urh|rhdtj	 |d< t
jd |d}|S )	Nc                 3  s    | ]} j t|j kV  qd S rB   )hosthttpxURL)ru   rooturlr?   r@   	<genexpr>   s   z*App.build_proxy_request.<locals>.<genexpr>zThis URL cannot be proxied.z	.hf.spaceBearer AuthorizationGETheaders)r   r   rY   anyZ	root_urlsPermissionErrorr   endswithr(   Zhf_tokenclientZbuild_request)rC   url_pathZis_safe_urlZ	is_hf_urlr   rp_reqr?   r   r@   build_proxy_request   s    

zApp.build_proxy_requestNzDict[str, Any] | None)rY   
app_kwargsr8   c              
     s  |pi }t js|dt tf i |  |  t jsP jtdgdgdgd  d dddd fd	d
} d dt	|fdd fdd}ddddd} d dddd fdd} d dddd fdd} 
d 
dt	 fd d! fd"d#} jd urP jjrPt   jd$td% jd$td%t	|fddd& fd'd(} jd)t	|gd* jd+t	|gd*d{d-d. fd/d0}	 jd1t	|gd* jd2t	|gd*dd3 fd4d5}
 d6dd7d8d9 d:dd7d;d<} d= fd>d?} jd@t	|gd* jd@t	|gd*ddA fdBdC} jdDt	|gd* jdDt	|gd*dddE fdFdG jdHt	|gd*ddIdIddJ fdKdL} jdMt	|gd*dddNfdOdP} 
dQ 
dRdSdT fdUdV}dWdXdIdY fdZd[ j
d\t	|gd* j
d]t	|gd* j
d^t	|gd* j
d_t	|gd*t	|fddWddd` fdadb} dct	|fdddd fdedf} jdgt	|gtdh fdidj} j
dkt	|gd*tdlfdmdn fdodp} dq dr fdsdt} jdutd% fdvdw} jdxtd% fdydz} S )|NZdefault_response_class*)Zallow_originsZallow_methodsZallow_headersz/userz/user/zfastapi.RequestzOptional[str])requestr8   c                   s$   | j dp| j d} j|S Naccess-tokenaccess-token-unsecurecookiesrh   rW   r   tokenappr?   r@   get_current_user   s    z(App.create_app.<locals>.get_current_userz/login_checkz/login_check/r=   userc                   s(    j d u s| d urd S ttjddd S )NzNot authenticatedstatus_codeZdetail)rX   r   r   HTTP_401_UNAUTHORIZEDr   r   r?   r@   login_check   s
    z#App.create_app.<locals>.login_checkr   )	websocketr8   c                   s   | j dp| j d}|S r   )r   rh   r   r   r?   r?   r@   ws_login_check   s    z&App.create_app.<locals>.ws_login_checkz/tokenz/token/r[   c                   s   | j d}| j|dS )Nr   )r   r   r   r   r   r?   r@   	get_token   s    z!App.create_app.<locals>.get_tokenz/app_idz/app_id/c                   s   d   jiS )Napp_id)r   r   r   r   r?   r@   r      s    zApp.create_app.<locals>.app_idz/loginz/login/r   )	form_datac                   s   | j  | j }} jd u r*tdtjdS t jsL| jv rL j| |ksdt jr j||rt	
d}| j|< tddid}|jd|dddd	 |jd
|dd |S tdddd S )N/r   r      successTr>   r   none)keyrR   httponlysamesitesecurer   )r   rR   r     zIncorrect credentials.r   )usernamestrippasswordrX   r#   r   HTTP_302_FOUNDrz   __call__rb   rc   rW   r   
set_cookier   )r   r   r   r   responser   r?   r@   login   s8    


zApp.create_app.<locals>.loginr   )response_class)r   r   c              
     s   t dd   }| jdd} jd u s4|d urH  j}||d< nd|j  j|d}z"|j	rjdnd	}t
|| |d
W S  ty } z(|j	rtd|n
td|W Y d }~n
d }~0 0 d S )Nzapplication/javascriptz.jsr    r   T)Zauth_requiredauth_messagespace_idr   zfrontend/share.htmlzfrontend/index.html)r   configzqDid you install Gradio from source files? Share mode only works when Gradio is installed through the pip package.znDid you install Gradio from source files? You need to build the frontend by running /scripts/build_frontend.sh)	mimetypesadd_typer   scoperh   rX   r   r   r   sharer4   ZTemplateResponser!   r   )r   r   rY   r   r   templateerrr   r?   r@   main  s<    

zApp.create_app.<locals>.mainz/info/)dependenciesz/infoTbool)	serializec                   s      j}tj|| S rB   )r   r   r3   rY   Zget_api_info)r   r   r   r?   r@   api_info*  s    
z App.create_app.<locals>.api_infoz/config/z/configr   c                   s$   | j dd}  j}||d< |S )Nr   r   r   )r   rh   r   r   )r   r   r   r   r?   r@   
get_config0  s    
z"App.create_app.<locals>.get_configz/static/{path:path})pathc                 S  s   t t| }t|S rB   )	safe_joinSTATIC_PATH_LIBr   )r   Zstatic_filer?   r?   r@   static_resource8  s    
z'App.create_app.<locals>.static_resourcez/assets/{path:path}c                 S  s   t t| }t|S rB   )r   BUILD_PATH_LIBr   )r   Z
build_filer?   r?   r@   build_resource=  s    
z&App.create_app.<locals>.build_resourcez/favicon.icoc                    s(      } | jd u rdS t| jS d S )Nzimg/logo.svg)r   r~   r   )rY   )r   r   r?   r@   faviconB  s    
zApp.create_app.<locals>.faviconz/proxy={url_path:path})r   c              
     sx   z  | }W n6 tyD } ztdt|d|W Y d }~n
d }~0 0 tj|ddI d H }t| |j|j	t
|jdS )Nr   r   Tstream)r   r   Z
background)r   r   r   r=   r   sendr$   Z	aiter_rawr   r   r"   aclose)r   r   r   Zrp_respr   r?   r@   reverse_proxyJ  s    (z%App.create_app.<locals>.reverse_proxyz/file={path_or_url:path})path_or_urlr   c                   s    }t| r t| tjdS t|  t fdd|jD }tdd  j	D } 
 }|sj|sj|r|tdd|  d  stdd	|  dt j}t t j|j v }t fd
d|jD }t j}	|s
|s
|s
|	s
tdd|  d|jdd }
|
drd|
v r|
dd  }
|
d\}}| r| rt|}t|}tj t||t|jt ! d}|S t" ddidS )Nr   c                 3  s   | ]}t  |V  qd S rB   r&   is_in_or_equal)ru   Zblocked_pathabs_pathr?   r@   r   e  s   z/App.create_app.<locals>.file.<locals>.<genexpr>c                 s  s   | ]}| d V  qdS ).N)
startswith)ru   partr?   r?   r@   r   i  rx     zFile not allowed: r     zFile not found: c                 3  s   | ]}t  |V  qd S rB   r   )ru   Zallowed_pathr   r?   r@   r   s  s   Ranger   zbytes=-   )stat_resultzAccept-Rangesr6   r   )#r   r&   Zvalidate_urlr#   r   r   abspathr   Zblocked_pathspartsis_dirr   existsr   r}   r=   r]   unionZtemp_file_setsZallowed_pathsrk   r   rh   r   r   split	isnumericintranged_responseZRangedFileResponseZ	OpenRanger[   rf   statr   )r   r   rY   Zin_blocklistZ
is_dotfiler   Z
in_app_dirZcreated_by_appZin_allowlistZwas_uploadedZ	range_valstartendr   r   r   r@   fileZ  sL    


zApp.create_app.<locals>.filez+/stream/{session_hash}/{run}/{component_id}r   )session_hashruncomponent_idr   c                   sF     j|  |i |d   d u r0tdd fdd}t| S )Nr   zStream not found.c                  3  s^   d} d}d}t  dkr8||kr$d S || 7 }t|  qd} d}|d u rRd S |V  qd S )Ng{Gz?x   r   )lentimesleeppop)Zcheck_stream_rateZmax_wait_timeZ	wait_timeZnext_streamr   r?   r@   stream_wrapper  s    

z6App.create_app.<locals>.stream.<locals>.stream_wrapper)r   pending_streamsrh   r   r$   )r   r   r   r   r  r   r   r@   r     s    
zApp.create_app.<locals>.streamz/file/{path:path}r   r   c                   s    | |I d H S rB   r?   r  )r   r?   r@   file_deprecated  s    z'App.create_app.<locals>.file_deprecatedz/reset/z/resetr*   bodyc              	     s|   | j  jvrddiS  j4 I d H < d  j| j  | j<  j| j  | j W d   I d H  qt1 I d H sj0    Y  ddiS )Nr   FT)r   r\   ra   fn_indexr^   addr  r   r?   r@   reset_iterator  s    >z&App.create_app.<locals>.reset_iteratorr)   zRequest | List[Request])r	  r   fn_index_inferredc                   sV  | j }t| dd }|d ur|| jvrBdd   j D  j|<  j| }| j| v rpi } j| | q j| }ni }i }t| dd }| j	}  j
| }	t|	d r|	d d nd }
t|
rֈ  j|
nd | j}|	d }| js|r|g}zt 4   j||||||||dI d H }W d    n1 s>0    Y  |d	d }t| drp| j| j |< t|tr|W n ty2 } z||d }|d urt|}  j| |i }| D ]}|d  qЈ  jpt|t}t  t d
|rt!|nd iddW  Y d }~S d }~0 0 | jsR|rR|d d |d< |S )Nr   c                 S  s.   i | ]&\}}t |d dr|tt |ddqS )ZstatefulFrR   N)getattrr	   )ru   Z_idblockr?   r?   r@   rw     s   z7App.create_app.<locals>.run_predict.<locals>.<dictcomp>event_idtargetsr   batch)r
  inputsr   stater\   r   r  
event_dataiteratorerror  r7   r   data)"r
  r  rZ   r   rY   itemsr^   remover\   r  r   r   r,   rh   r  batchedr&   ZMatplotlibBackendManangerZprocess_apir  r{   r   
isinstancer+   BaseExceptionidr  valuesappend
show_error	traceback	print_excr   r=   )r	  r   r  r
  r   Zsession_stater\   r  	raw_input
dependencytargetr  r  outputr  r  Zrun_idr  r   r#  r   r?   r@   run_predict  sv    



,

z#App.create_app.<locals>.run_predictz/run/{api_name}z/run/{api_name}/z/api/{api_name}z/api/{api_name}/)api_namer	  r   r   c           	        s*  d }|j d u r\t jD ]\}}|d | kr|} q:q|d u rbtdd|  diddS n|j } js |rdj |j	dkrt
tjd	d
 j| d r|jg|_|jr|jr fdd|jD }n$t|jtsJ tf d i|j}nt |d}|||dI d H }|S )Nr+  r  zThis app has no endpoint /api/z/.r  r  r   r   z Not authorized to skip the queuer   Zcancelsc                   s   g | ]}t f d  i|qS r   )Request)ru   reqr,  r?   r@   
<listcomp>6  s   z3App.create_app.<locals>.predict.<locals>.<listcomp>r   )r   r   )r	  r  r   )r
  	enumerater   r   r   Zapi_openZqueue_enabled_for_fnrd   r   rh   r   r   r   r   r  r   r  r  r[   r-  )	r+  r	  r   r   r  ifnZ
gr_requestresult)r   r*  r,  r@   predict  sN    



zApp.create_app.<locals>.predictz/queue/joinr   c           	        s      } jd ur2|d u r2| jtjdI d H  d S |jjd u rXtt| j	}|j
| |  I d H  z"tj| ddiddI d H  W n ty   Y d S 0 ztj|  ddI d H }W n ty   Y d S 0 t| |d |d }||_|d |_|j|j dd	rvt|j d
|j hI d H  |j|j|jI d H  |jj| t|jj|gd}t||j|jdd n`|j|}|d u r|j|ddiI d H  |  I d H  d S |j! }|j"|||I d H  t#dI d H  | j$t%j&krd S qd S )N)codemsgZ	send_hash   )timeoutr   r
  Zeveryr   _F)r  Z
queue_fullrt   )'r   rX   closer   ZWS_1008_POLICY_VIOLATIONry   Zserver_pathget_server_url_from_ws_urlr=   r   set_urlacceptr_   wait_forZ	send_jsonAsyncTimeOutErrorZreceive_jsonr/   r   r   r   r
  rh   r0   Zreset_iteratorsZcontinuous_tasksr"  r1   Zprocess_eventsr2   pushsend_messageZ
disconnectget_estimationZsend_estimationr  Zapplication_stater%   ZDISCONNECTED)	r   r   rY   Zapp_urlZsession_infoeventZtaskZrankZ
estimationr   r?   r@   
join_queueE  sV    


z"App.create_app.<locals>.join_queuez/queue/status)r   Zresponse_modelc                     s      j S rB   )r   ry   rB  r?   r   r?   r@   get_queue_status  s    z(App.create_app.<locals>.get_queue_statusz/upload.zList[UploadFile]r   c                   s4   g }t  }| D ]}||| jI d H  q|S rB   )r3   r   r"  Zsave_uploaded_filerk   )r   Zoutput_filesZfile_managerZ
input_filer   r?   r@   upload_file  s    z#App.create_app.<locals>.upload_filestartupz/startup-eventsc                     s     j s    d _ dS dS NTF)re   r   startup_eventsr?   r   r?   r@   rI    s
    z&App.create_app.<locals>.startup_eventsz
/theme.cssc                     s   t   jddS )Nztext/css)rJ   )r   r   	theme_cssr?   r   r?   r@   rJ    s    z!App.create_app.<locals>.theme_cssz/robots.txtc                     s      jrdS dS d S )NzUser-agent: *
Disallow: /zUser-agent: *
Disallow: )r   r   r?   r   r?   r@   
robots_txt  s    
z"App.create_app.<locals>.robots_txt)T)r'   ZIS_WASMrl   r5   rU   r   Zadd_middlewarer   rh   r   postrY   Zexpects_oauthr-   headr   r   r.   r   on_eventr   )rY   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r4  rD  rE  rF  rI  rJ  rK  r?   )r   r   r*  r   r@   
create_app   s    
  $0P$4;zApp.create_app)N)rG   rH   rI   __doc__rn   r   r   r   rK   rO  __classcell__r?   r?   rp   r@   rU   g   s    rU   r=   )rT   r   r8   c                   s   dd t jjt jjfD }|dkr*tdt| t j|  }t fdd|D st j	 s dks 
dst j|rtd	t j|std
d|S )ztSafely path to a base directory to avoid escaping the base directory.
    Borrowed from: werkzeug.security.safe_joinc                 S  s    g | ]}|d ur|dkr|qS )Nr   r?   ru   sepr?   r?   r@   r/    s   zsafe_join.<locals>.<listcomp>r   r   c                 3  s   | ]}| v V  qd S rB   r?   rR  filenamer?   r@   r     rx   zsafe_join.<locals>.<genexpr>z..z../r   r   zFile not found)rf   r   rS  altsepr   	posixpathnormpathjoinr   isabsr   isdirr   )rT   r   Z_os_alt_sepsfullpathr?   rT  r@   r     s*    



r   z
List[Type])cls_setc                 C  sz   g }g }| D ]d}t |pd}|d}|D ]*}d|v r,||dd dd  q,||d dd  q||fS )	Nr   
zvalue (rt   )r   :)inspectgetdocr   r"  )r]  ZdocsettypesclsdocZ	doc_linesliner?   r?   r@   	get_types  s    
 rh  )ws_urlc                 C  sR   t | }|jdkrdnd}|jr,d|j nd}| d|j | |jdd S )Nwshttphttpsr`  r   z://z
queue/join)r   schemeporthostnamer   rQ   )ri  Zws_url_parsedrm  rn  r?   r?   r@   r;    s    r;  Zroutesc                   @  sr   e Zd ZdZdd Zdd Zdd Zdd	 Zd
dddZdd Z	dd Z
dd ZddddZddddZdS )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                 C  sD   | j | | D ]*\}}t|ttfr2t|}t| || qd S rB   )__dict__updater  r  r[   listrp  setattr)rC   Zdict_r   rR   r?   r?   r@   rn     s
    zObj.__init__c                 C  s
   | j | S rB   rq  )rC   itemr?   r?   r@   __getitem__  s    zObj.__getitem__c                 C  s   || j |< d S rB   ru  rC   rv  rR   r?   r?   r@   __setitem__  s    zObj.__setitem__c                 c  s<   | j  D ],\}}t|tr,|t|fV  q
||fV  q
d S rB   )rq  r  r  rp  r[   )rC   r   rR   r?   r?   r@   __iter__  s    
zObj.__iter__r   r   c                 C  s:   || j v rdS | j  D ]}t|tr||v r dS qdS rH  )rq  r!  r  rp  rx  r?   r?   r@   __contains__  s    
zObj.__contains__c                 C  s
   | j  S rB   )rq  keysr   r?   r?   r@   r|    s    zObj.keysc                 C  s
   | j  S rB   )rq  r!  r   r?   r?   r@   r!  
  s    z
Obj.valuesc                 C  s
   | j  S rB   )rq  r  r   r?   r?   r@   r    s    z	Obj.itemsr=   c                 C  s
   t | jS rB   r=   rq  r   r?   r?   r@   __str__  s    zObj.__str__c                 C  s
   t | jS rB   r}  r   r?   r?   r@   __repr__  s    zObj.__repr__N)rG   rH   rI   rP  rn   rw  ry  rz  r{  r|  r!  r  r~  r  r?   r?   r?   r@   rp    s   rp  c                   @  s2   e Zd ZdZddddddZdd	 Zd
d ZdS )r-  a  
    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`, and `path_params`. If
    auth is enabled, the `username` attribute can be used to get the logged in user.
    Example:
        import gradio as gr
        def echo(name, request: gr.Request):
            print("Request headers dictionary:", request.headers)
            print("IP address:", request.client.host)
            return name
        io = gr.Interface(echo, "textbox", "textbox").launch()
    Nzfastapi.Request | None
str | None)r   r   c                 K  s   || _ || _|| _dS )z
        Can be instantiated with either a fastapi.Request or by manually passing in
        attributes (needed for websocket-based queueing).
        Parameters:
            request: A fastapi.Request
        N)r   r   ro   )rC   r   r   ro   r?   r?   r@   rn   (  s    zRequest.__init__c                 C  s&   t |trtjt|tdS |S d S )N)object_hook)r  r[   jsonloadsr<   rp  )rC   dr?   r?   r@   dict_to_obj8  s    
zRequest.dict_to_objc              
   C  sl   | j r| t| j |S z| j| }W n6 ty\ } ztd| d|W Y d }~n
d }~0 0 | |S d S )Nz#'Request' object has no attribute 'rO   )r   r  r  ro   KeyErrorAttributeError)rC   nameobjZker?   r?   r@   __getattr__>  s    
zRequest.__getattr__)NN)rG   rH   rI   rP  rn   r  r  r?   r?   r?   r@   r-    s     r-  zfastapi.FastAPIrr   r  zdict[str, Any] | None)r   rY   r   gradio_api_urlr   r8   c                   sN   d|_ | |_|  tj||d| d fdd}| | | S )a  Mount a gradio.Blocks to an existing FastAPI application.

    Parameters:
        app: The parent FastAPI application.
        blocks: The blocks object we want to mount to the parent app.
        path: The path at which the gradio application will be mounted.
        gradio_api_url: The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/'
        app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
    Example:
        from fastapi import FastAPI
        import gradio as gr
        app = FastAPI()
        @app.get("/")
        def read_main():
            return {"message": "This is your main app"}
        io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
        app = gr.mount_gradio_app(app, io, path="/gradio")
        # Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
    F)r   rG  c                     s.     jr* r  j      d S rB   )r   Zenable_queuery   r<  rI  r?   r  Z
gradio_appr?   r@   start_queuek  s    
z%mount_gradio_app.<locals>.start_queue)dev_modeZget_config_filer   Zvalidate_queue_settingsrU   rO  rN  mount)r   rY   r   r  r   r  r?   r  r@   mount_gradio_appK  s    
r  )NN)qrP  
__future__r   r_   sysversion_infoimportlib.resourcesr   Zimportlib_resourcesrb  r  r   rf   rW  rb   ri   r  r$  r   r?  collectionsr   copyr	   pathlibr
   typingr   r   r   r   r   urllib.parser   Zfastapir   rP   r;   r   r   r   r   r   r   r   Zfastapi.middleware.corsr   Zfastapi.responsesr   r   r   r   Zfastapi.securityr   Zfastapi.templatingr   Zgradio_client.documentationr   r    Zjinja2.exceptionsr!   Zstarlette.backgroundr"   Zstarlette.responsesr#   r$   Zstarlette.websocketsr%   r3   Zgradio.ranged_responser   r&   r'   Zgradio.contextr(   Zgradio.data_classesr)   r*   Zgradio.exceptionsr+   Zgradio.helpersr,   Zgradio.oauthr-   Zgradio.queueingr.   r/   Zgradio.utilsr0   r1   r2   initjoinpathas_posixZSTATIC_TEMPLATE_LIBr   r   	read_textVERSIONr5   rS   r4   envfiltersZAsyncClientr   rU   r   rh  r;  rp  r-  r  r?   r?   r?   r@   <module>   s   
$

    P23  