
    wi{                      d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlmZ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!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-m.Z.m/Z/m0Z0m1Z1m2Z2 dd
l3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZI ddlJmKZK ddlLZLddlLmMZMmNZNm;Z;mOZO ddlPmQZQ ddlRmSZS ddlTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` ddlambZbmcZc ddldmeZe ddlfmgZg ddlhmiZi ddljmkZk ddllmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZx ddlymzZz dd l{m|Z|m}Z}m~Z~mZmZmZmZ dd!lmZ dd"lmZmZmZmZ erdd#lmZ ddlZddlZddlZ ej                      e eYej                            d$                              d%                                                    Z e eYej                            d$                              d&                                                    Z e eYej                            d$                              d'                                                    Z e            Zh d(Zej                            d)          p# e e ej                              d$z            Z G d* d+e/          Zd, Z e6e-          Zeej        j        d.<    e"j         e"j        d/d01           e"j        d2          3          Z eo            Z G d4 d5e)          Zd6 Zdjd=Zdkd@Z e>            	 	 	 	 dlddddddddCdddddddddDdmdh            Zg diZdS )nzImplements 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)AsyncIteratorCallable)Path)Empty)TYPE_CHECKINGAnyLiteralUnioncast)	APIRouterBackgroundTasksBodyDependsFastAPIHTTPExceptionstatus)FileResponseHTMLResponseJSONResponsePlainTextResponseResponseStreamingResponse)OAuth2PasswordRequestForm)Jinja2Templates)	WebSocketWebSocketDisconnect)utils)document)ServerMessage)TemplateNotFound)parse_options_header)BackgroundTask)
UploadFile)RedirectResponse)ranged_responseroute_utilsr   
wasm_utils)BrotliMiddleware)Context)
CancelBodyComponentServerBlobBodyComponentServerJSONBodyDataWithFilesDeveloperPathPredictBodyPredictBodyInternal	ResetBodySimplePredictBodyUserProvidedPathVibeCodeBodyVibeEditBody)ErrorInvalidPathError)special_args)I18n)start_node_server)attach_oauth)
API_PREFIXCustomCORSMiddlewareFileUploadProgress FileUploadProgressNotQueuedError!FileUploadProgressNotTrackedErrorGradioMultiPartParserGradioUploadFileMultiPartExceptionRequestcompare_passwords_securelycreate_lifespan_handlermove_uploaded_files_to_cache)process_video_with_ffmpeg)CloseStreamMessageEstimationMessageEventMessageHeartbeatMessageProcessCompletedMessageProcessGeneratingMessageUnexpectedErrorMessage)StateHolder)cancel_tasksget_node_pathget_package_versionget_upload_folder)Blockgradio	templatesztemplates/frontend/staticztemplates/frontend/assets>   	audio/ogg	audio/wav	image/gif	video/ogg
audio/mpeg
image/jpeg
image/webp
text/plain
video/webm	image/png	video/mp4application/jsonGRADIO_TEMP_DIRc                  J    e Zd ZdZedd            ZddZedd	            Zd
S )ORJSONResponserd   contentr	   returnbytesc                h    t          j        | t           j        t           j        z  t                    S )Noptiondefault)orjsondumpsOPT_SERIALIZE_NUMPYOPT_PASSTHROUGH_DATETIMEstrrh   s    ]/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/gradio/routes.py_renderzORJSONResponse._render   s/    |-0OO
 
 
 	
    c                6    t                               |          S N)rg   rv   )selfrh   s     ru   renderzORJSONResponse.render   s    %%g...rw   rs   c                \    t                               |                               d          S )Nutf-8)rg   rv   decodert   s    ru   _render_strzORJSONResponse._render_str   s$    %%g..55g>>>rw   N)rh   r	   ri   rj   )rh   r	   ri   rs   )__name__
__module____qualname__
media_typestaticmethodrv   r{   r    rw   ru   rg   rg      sk        #J
 
 
 \
/ / / / ? ? ? \? ? ?rw   rg   c                    t          j        t                              |                               dd                              dd                              dd                              dd                    S )	N<z\u003c>z\u003e&z\u0026'z\u0027)
markupsafeMarkuprg   r   replace)values    ru   toorjsonr      sd    ""5))	i	 	 	i	 	 	i	 	 	i	 	   rw   )	directoryr   d      )max_connectionsmax_keepalive_connectionsg      $@)limitstimeoutc                       e Zd ZdZdZ	 d'd( fdZ ej                    Ze		 	 d)d*d            Z
d+dZd,dZd Zd Ze		 d'd-d            Ze		 	 	 	 	 d.d/d&            Z xZS )0Appz
    FastAPI App Wrapper
    Nauth_dependency.Callable[[fastapi.Request], str | None] | Nonec                   i | _         d | _        t          j        d          | _        d| _        d | _        t                      | _        i | _	        t                      | _        t          j                    | _        t          j                    | _        t          j        d          | _        t          j        d          | _        d| _        t)                      | _        d| _        d | _        d | _        g | _        || _        d | _        d | _        |                    dd            |                    dd            i | _         t?                      j         di | d S )N   F    r   docs_url	redoc_urlr   )!tokensauthsecretstoken_urlsafeanalytics_keymonitoring_enabledblocksrQ   state_holder	iteratorssetiterators_to_resetr   safe_get_locklocksafe_get_stop_event
stop_event	cookie_idqueue_tokenstartup_events_triggeredrU   uploaded_file_dirchange_countchange_typereload_error_message_asyncio_tasksr   api_infoall_app_info
setdefaultcustom_component_hashessuper__init__)rz   r   kwargs	__class__s      ru   r   zApp.__init__   s?   
 	$2266"',0'MM35,/EE'))	355 .r22"044(-%!2!4!4!">B04!24.  	*d++++t,,,79$""6"""""rw   http requestfastapi.Requestserver_namers   	node_portintpython_portschememounted_pathri   r   c                  K   | j         j        }|r|                    |d          }| j         j        r|d| j         j         z  }| d| d| | }| d| }|r|d| z  }|r||z  }t	          | j                  }	||	d<   t          |          |	d<   t          j        d          rd|	d	<   t          j
                            | j        t          j        |          |	
          }
t          j
                            |
d           d {V }t!          |                                |j        |j        t'          |j                            S )Nr   ?z://:zx-gradio-serverzx-gradio-portGRADIO_LOCAL_DEV_MODE1zx-gradio-local-dev-modeheadersTstreamstatus_coder   
background)urlpathr   querydictr   rs   osgetenvr   clientbuild_requestmethodhttpxURLsendr   	aiter_rawr   r#   aclose)r   r   r   r   r   r   	full_pathr   
server_urlr   new_requestnode_responses               ru   proxy_to_nodezApp.proxy_to_node  s      K$	 	<!)),;;I; 	10W[.000I@@K@@)@Y@@00;00
 	,+k+++J 	',&Jw''%/!"#&{#3#3 9,-- 	514G-.j..NEIcNNG / 
 
 "jook$oGGGGGGGG ##%%%1!)%m&:;;	
 
 
 	
rw   r   gradio.BlocksNonec                ,   |j         }|)t          |          sd |D             | _         n|| _         nd | _         || _        t          j                    | _        |j        | _        i | _        |j        pd| _        | j	        
                    |           d S )Nc                ,    i | ]}|d          |d         S )r      r   ).0accounts     ru   
<dictcomp>z%App.configure_app.<locals>.<dictcomp>/  s"    HHHWQZHHHrw   r   )r   callabler   r   getcwdcwdfavicon_pathr   	root_pathr   
set_blocks)rz   r   r   s      ru   configure_appzApp.configure_app+  s    {D>> !HH4HHH		 		DI9;;"/)/R$$V,,,,,rw   c                <    | j         t          d          | j         S )Nz+No Blocks has been configured for this app.)r   
ValueError)rz   s    ru   
get_blockszApp.get_blocks<  s!    ;JKKK{rw   c                `   t          j        |          | j        sJ t          fd| j        j        D                       }|st          d          j                            d          }i }t          j	        |rdt          j	         |d<   t                              d|          }|S )Nc              3  \   K   | ]&}j         t          j        |          j         k    V  'd S ry   )hostr   r   )r   rootr   s     ru   	<genexpr>z*App.build_proxy_request.<locals>.<genexpr>F  sF       
 
15CH	$,,
 
 
 
 
 
rw   zThis URL cannot be proxied.z	.hf.spacezBearer AuthorizationGETr   )r   r   r   any
proxy_urlsPermissionErrorr   endswithr*   hf_tokenr   r   )rz   url_pathis_safe_url	is_hf_urlr   rp_reqr   s         @ru   build_proxy_requestzApp.build_proxy_requestA  s    i!!{{  
 
 
 
9=9O
 
 
 
 
  	A!"?@@@H%%k22	'I''C1A'C'CGO$%%eS'%BBrw   c                P    | j         D ]}|                                 g | _         d S ry   )r   cancel)rz   tasks     ru   _cancel_asyncio_taskszApp._cancel_asyncio_tasksR  s1    ' 	 	DKKMMMM rw   
app_kwargsdict[str, Any]
mcp_serverbool | Nonec                    t           dz   }|6t          j                            dd                                          dk    }|r	 dd l}n"# t          $ r}t          d          |d }~ww xY w	 |j                                        _	        d _
        d d|v r|d         t          j        d fd            }||d<   n(# t          $ r}d _
        d|  _        Y d }~nd }~ww xY w                                  _        |S )Nz/mcpGRADIO_MCP_SERVERFalsetruer   zIn order to use `mcp_server=True`, you must install gradio with the `mcp` extra. Please install it with `pip install "gradio[mcp]"`Tlifespanappr   c               R  K   t          j                    4 d {V }j        r3|                    j                            |                      d {V  $|                     |                      d {V  d W V  d d d           d {V  d S # 1 d {V swxY w Y   d S ry   )
contextlibAsyncExitStackmcp_server_objenter_async_contextr  )r  stackr   user_lifespans     ru   	_lifespanz'App.setup_mcp_server.<locals>._lifespann  si     )8::       e!0 "'";"; & 5 > >s C C# #        )4"'";";MM#<N<N"O"OOOOOOOO                             s   A&B
B #B FzError launching MCP server: )r  r   )r=   r   environgetlower
gradio.mcpImportErrormcpGradioMCPServerr  r  r  asynccontextmanager	Exception	mcp_errorget_config_fileconfig)r   r  r  mcp_subpathrW   er   r  s   `      @ru   setup_mcp_serverzApp.setup_mcp_serverW  s    !6)(;WEEKKMMQWWJ 	F!!!!!   ! Z F(.
(B(B6(J(J%$(! $++$.z$:M/      0/ *3
:&& F F F$)!#E!#E#E      F
 ""$$ 	 s1   A 
A,A''A,0AC 
C(C##C(TFdict[str, Any] | Nonestrict_corsboolssr_modec           	     T   56789:;<=>?@ |pi }|                     dt                     t                               ||          } j        pd}t          |                    dd           g|R  |d<   t          dd|i|ddi6 j        r! j                            6| j	                   t          t                    }6                                t          j        s:6                    t           |           6                    t"          d	|g
           |r!6                    d          dň fd            }	|                    d          |                    d          dƈ6fd                        9|                    d          |                    d          t'          9          fdǈ6 fd                        }
|                    d          |                    d          dȈ6fd                        }|                    d          |                    d          dȈ6fd                        }|                    d t'          |
          g!          dň6fd"            }6                    d#          6                    d$          t'                      fdɈ6fd'                        }6j        6j        j        rt/          6           n06                    d(          t'          9          fdʈ6fd)            }6                    d*          dd,            }69<fd-} j        D ]}|d.         }|d/k    r ||           	 dd͈6fd4;6                    d5t4          6          6                    d5t4          6          t'          9          d/d/fdΈ56;fd7                        <6                    d8          dψ6fd:            }|                    d;t'          |
          g!          |                    d<t'          |
          g!          dň6fd=                        5|                    d>t'          |
          g!          dň56fd?            }6                    d@t'          |
          g!          6                    dAt'          |
          g!          ddш6 9;fdB                        }6                    dC          ddD            ?|                    dE          d҈6fdL            }6                    dM          ddN            }6                    dO          6?fdP            }|                    dQt'          |
          g!          |                    dQt'          |
          g!          dӈ6fdS                        }|                    dTt'          |
          g!          |                    dTt'          |
          g!          dԈ6fdV                        8|                    dW          dՈ6fd[            }|                    dW          dֈ6fd^            }|                    d_          d׈6fd`            }|                    da          d؈6fde            }|                    df          dو6fdi            }|                    dj          d؈6fdk            }|                    dlt'          |
          g!          dڈ8fdm            }|                    dn          |                    do          ddq                        }|                    dr          t'          9          fd܈6fdv            }|                    dwt'          |
          g!          |                    dxt'          |
          g!          |                    dyt'          |
          g!          |                    dzt'          |
          g!          t'          9          fd݈6fd|                                                }|                    d}t'          |
          g!          |                    d~t'          |
          g!          t'          9          fdވ6>fd                        } |                    dt'          |
          g!          t'          9          fd߈>fd            }!d߈6fd>|                    d          d6fd            }"|                    dt'          |
          g!          d=fd            }#|                    dt'          |
          g!          d=fd            }$d6fd=dd:|                    dt'          |
          g!          |                    dt'          |
          g!          dň6:fd                        }%|                    dt'          |
          gt8                    6fd            }&|                    d          dd            }'|                    dt'          |
          g!          	 dd6 fd            }(|                    d          6fd            })|                    dt:          6          6                    dt:          6          6fd                        }*6                    dt:          6          6fd            }+6                    d          6                    d          dd6fd                        },6                    d          6 fd            }-6                    dt'          |
          g!          dň6 fd            }.6                    d          6fd            }6                    d          d6 fd            }/|                    dt'          |
          g!          dň7fd            }0t=          t>                    dz  @@                     dd           |                    d          |                    d          d @fd                        }1|                    d          |                    d          tC          dd          fd @fd                        }2|                    d          |                    d           fd                        }3|                    d          |                    d          d fd                        }4dÄ 76"                    |           6S )Ndefault_response_class)NNr  r   debugT)prefix)r1     )qualityexcluded_handlersr   r   r   c                |  K   j         }|'| j        j                            j         pdd          n| j        j        t	          dd           ىj        t          fdt          D                       st          j	        8| j        j
        p!t          t          j        dd                    t          _	        	 t                              | j        pdj        t          j	        | j        j        |pd           d {V S # t"          $ r}t%          |           Y d }~nd }~ww xY w ||            d {V }|S )Nr   node_processc              3  H   K   | ]}                     d |           V  dS )/N)
startswith)r   r   r   s     ru   r   zIApp.create_app.<locals>.conditional_routing_middleware.<locals>.<genexpr>  s5      VVs	C		 : :VVVVVVrw   GRADIO_SERVER_PORT78600.0.0.0)custom_mount_pathr   r   r   getattrr   r  INTERNAL_ROUTESr   app_portportr   r   r   r   node_server_namer   r)  print)r   	call_nextrC  r.  responser   r   s        @ru   conditional_routing_middlewarez6App.create_app.<locals>.conditional_routing_middleware  s      %+$<! )4 K$,,V-E-KRPPP )  FND99E(4VVVVoVVVVV 5 |+'.{'7 (3I&:FCC< <
!%(%6%6#"3@y",L#K.-3& &              % ! ! !a!!*7!3!3333333s   >AD 
D(D##D(z/userz/user/ri   
str | Nonec                    j                              |           S | j                            dj                   p!| j                            dj                   }j                            |          S )Naccess-token-access-token-unsecure-)r   cookiesr"  r   r   r   tokenr  s     ru   get_current_userz(App.create_app.<locals>.get_current_user  s     ".**7333O''///  O$$%Mcm%M%MNN  :>>%(((rw   z/login_checkz/login_check/userrs   c                n    j         j        | d S t          t          j        dj        d          )NNot authenticatederrorauth_messager   detail)r   r   r   r   HTTP_401_UNAUTHORIZEDrZ  )rU  r  r   s    ru   login_checkz#App.create_app.<locals>.login_check  sO      S%8%@TEU"80$*$7    rw   z/tokenz/token/r   c                    | j                             dj                   }|j                            |          dS )NrO  )rS  rU  )rQ  r"  r   r   rR  s     ru   	get_tokenz!App.create_app.<locals>.get_token  sA     O''(G(G(GHHE"CJNN5,A,ABBBrw   z/app_idz/app_id/c                :    d                                 j        iS )Napp_id)r   rb  )r   r  s    ru   rb  zApp.create_app.<locals>.app_id  s     cnn..566rw   z/dev/reload)dependenciesc                H   K   dfd}t           ||           d          S )Nr   r   c                 K   d}d}t          j                    }j        }	 |                                  d {V rd S j        |k    r?j        }j        dk    rt          j        j                   nd}dj         d| dW V  t          j	        |           d {V  t          j                    |z
  |k    rd	W V  t          j                     })
N   皙?TrY  z{}event: 
data: 

zevent: heartbeat
data: {}

)
timeperf_counterr   is_disconnectedr   jsonrp   r   asynciosleep)r   heartbeat_rate
check_ratelast_heartbeatcurrent_countmsgr  s         ru   reload_checkerz>App.create_app.<locals>.notify_changes.<locals>.reload_checker  s     !#!
!%!2!4!4 # 05$4466666666 '=88(+(8  #'99 !J#*B'DEEE!% 
 O#/NN3NNNNNNN!-
333333333(**^;nLLBBBBB)-!5rw   text/event-streamr   r   r   )r   )r   rv  r  s     ru   notify_changesz&App.create_app.<locals>.notify_changes  sN      5 5 5 5 5 50 %w''.   rw   /loginz/login/	form_datar   c                   |j                                         |j        }}j        7t	          j        | dj                  }t          |t          j	                  S t          j                  s$|j        v rt          |j        |                   s/t          j                  rj                            ||          rtt          j        d          }|j        |<   t!          ddi          }|                    dj         |dd	d
           |                    dj         |d           |S t'          dd          )Nr{  r   
route_pathr   r   r   r   successTrt   rO  none)keyr   httponlysamesitesecurerP  )r  r   r    zIncorrect credentials.r[  )usernamestrippasswordr   r'   get_root_urlr   r%   r   HTTP_302_FOUNDr   rF   __call__r   r   r   r   
set_cookier   r   )r   r|  r  r  r   rS  rK  r  s          ru   loginzApp.create_app.<locals>.login  s}   
 "+!3!9!9!;!;Y=OhHx"/#'!m  
 (Df>STTTTSX&&V((.x(9KLL )38$$ )),):):8X)N)N )  -b11$,
5!'D0ABBB##777!# $    ##@@@! $   
  #<TUUUUrw   /logoutc                v   t          j        | dj                  }t          |t          j                  }|                    dj         d           |                    dj         d           t          j	        
                                          D ]}j	        |         |k    rj	        |= |S )Nr  r~  r  rO  r>  )r  r   rP  )r'   r  r   r%   r   r  delete_cookier   listr   keys)r   rU  r   rK  rS  r  s        ru   logoutzApp.create_app.<locals>.logout;  s    "/#(!m  
 ,&BWXXX&&+J3=+J+JQT&UUU&&@@@s '    "#*//"3"344 . .Ez%(D00Ju-rw   z/svelte/{path:path}r   c           	         t          t                    dz  }t          t          t	          t          |                    t          |                               S )Nsvelte)r   BUILD_PATH_LIBr   routes_safe_joinr/   rs   r4   )r   svelte_paths     ru   _zApp.create_app.<locals>._Q  sQ    ~..9K !#k"2"2335Ed5K5K   rw   c                                          d  t                                         d  dt                    t                    dfd
 fd	                        }d S )Nr>  response_classr   r   r   rU  rs   	deep_linkc                      | ||          S ry   r   )r   rU  r  mainpages      ru   
page_routez7App.create_app.<locals>.attach_page.<locals>.page_route[  s     tGT4;;;rw   )r   r   rU  rs   r  rs   )r"  r   r   )r  r  r  rT  r  s   ` ru   attach_pagez#App.create_app.<locals>.attach_pageZ  s    WWZZZW==WW[[[[W>> $$455!#< < < < < < < ?> >=< < <rw   r   r   r  r,  r  r  c                J   d         }	 t          j                  dz  | z  dz  }|                                r)t          j        |                                          }d}nd}n&# t          t          t          j        f$ r d}g }Y nw xY wrfd|D             }||fS )N
components
deep_links
state.jsonvalidinvalidc                L    g | ] }|d          d                  d         v |!S idr  r  r   r   	componentr,  r  s     ru   
<listcomp>z:App.create_app.<locals>.load_deep_link.<locals>.<listcomp>~  @       ! &.*>|*LLL LLLrw   )	r   r   existsro   loads
read_bytesFileNotFoundErrorOSErrorJSONDecodeError)r  r,  r  r  r   deep_link_stater  s    ``   ru   load_deep_linkz&App.create_app.<locals>.load_deep_linki  s      -J .//"#  ##  ;;== 0!'doo.?.?!@!@J&-OO&/O%w0FG      "+


       %/  

 ..s   AA* * BBr>  r  c           
        t          j        dd                                           }t          j        | d j        p|j                  }j        j        |t          j
        |j                  d}fdd         D             }|r |          \  }}|d<   |d	<   |d<   fd
                    dg           D             d<   d                  d         d<   d<   t          j        |          nEj        r#t          t          j        d|j        d          d|j        |j        |ddi iidgg g dd		 |j        rdnd} |           }	t(                              | ||	d          }
|
S # t,          $ r,}|j        rt/          d          |t/          d          |d }~ww xY w)Nzapplication/javascriptz.jsr>  r~  r  c                L    g | ] }|d          d                  d         v |!S r  r   r  s     ru   r  z0App.create_app.<locals>.main.<locals>.<listcomp>  r  rw   r  r  r  c                L    g | ] }|d          d                  d         v |!S )r  r  rc  r   )r   
dependencyr,  r  s     ru   r  z0App.create_app.<locals>.main.<locals>.<listcomp>  sA     * * *"!$'6&>$+?+OOO OOOrw   rc  r  layoutcurrent_pagerW  rX  r[  Tr   )	auth_requiredrZ  space_idr   r  pagesr  rc  r  zfrontend/share.htmlzfrontend/index.html)r,  gradio_api_info)r   namecontextzqDid 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   r'   r  r   rC  r   r   r   safe_deepcopyr,  r"  update_root_in_configr   r   r]  rZ  r  sharerX   TemplateResponser!   r   )r   rU  r  r  r   r   r  r  templater  resperrr,  r   r  r  s     `         @ru   r  zApp.create_app.<locals>.main  s    7???^^%%F+%t::-C6+C  D
  S%8%@TEU,V];;"(    %+L%9  

  2@.!3 3/J
 &*z",;()'1|$* * * * *&,jj&D&D* * *~&
 $*&>$#7#Ax )-~& %:64HH$ # & <!4(.(;     &*$*$7 & (B0 T"$$&$&
 
-3\T))?T  #+(7"3"3 11#!"(+:  2   # 
 
 
< 	$R  
 %M  
s   7F
 

G 'F;;G z/gradio_api/deep_linksession_hashc                   | j         v rd j         |          j        D             }t          j        |t          j        t          j        z  t                    }t          j        |          }t          j
                  dz  |z  }|                    dd           t          |dz  d          5 }|                    |           d d d            n# 1 swxY w Y   |S dS )	Nc                6    g | ]}t          j        |          S r   )r   r  )r   cs     ru   r  z5App.create_app.<locals>.deep_link.<locals>.<listcomp>  s3        '**  rw   rl   r  T)parentsexist_okr  wbr   )r   r  ro   rp   rq   rr   rs   r'   create_url_safe_hashr   r   mkdiropenwrite)r  r  components_jsonr  r   fr  s         ru   r  z!App.create_app.<locals>.deep_link  s,   s///  -l;F  
 #),!58WW# # #
 (<_MM	 !677,FR	t<<<)l2D99 -QGGO,,,- - - - - - - - - - - - - - -  rs   2CCCz/info/z/infoc                   | j                             dd          }|r;j        s-                                                    d          _        j        S j        szt          j                                                                                  }t          t          t          t          f         |          }t          j        |          }|_        j        S )Nall_endpointsFT)r  )query_paramsr"  r   r   get_api_infor   r   r  r   r   rs   r	   r'   'update_example_values_to_use_public_url)r   r  r   r  s      ru   r   z App.create_app.<locals>.api_info  s     $044_eLLM (' Y'*~~'7'7'D'DSW'D'X'XC$''< ( .s~~/?/?/L/L/N/NOOS#X99&NxXX'<rw   z/openapi.jsonc                    |           }dt                                          dd          t                                          dd          t          di di id}|                    d	i                                           D ]|\  }}|                    d
d          sd|                    dd|           |                    dd          |                    d                              dd          ddddi diiddddddi diididi}|d         d         d         d         d         d         }|                    dg           D ]}|d         }|                    di           }	d|	v r%t          |	          }	|	                    dd            d|	v rd|	vrt          |	          }	d|	d<   |	||<   d!|v rrd"|d         d         d         d         vr!d#d$i ii|d         d         d         d         d"<   |d!         |d         d         d         d         d"         d#         d$         |<   |d         d%         d         d         d         d         d         }
t          |                    d&g                     D ]r\  }}|d'k    rd(| nd)}|                    di           }d|v r%t          |          }|                    dd            d|v rd|vrt          |          }d|d<   ||
|<   s||d*         d+| <   ~|S ),z:Generate an OpenAPI schema from the Gradio app's API info.z3.0.2titlez
Gradio Appdescriptionr   )r  r  versionschemas)openapiinfopathsr  named_endpointsshow_apiTpostz	Endpoint r>  r  rd   schemaobject)type
properties)requiredrh   200zSuccessful response)r  rh   )summaryr  operationIdrequestBody	responsesr  rh   r  
parametersparameter_namer  additional_descriptionNexample_inputexamplesexample1r   r  returnsr   output_outputr  z/run)
rD  r   VERSIONr"  itemsr  r   r   pop	enumerate)r   r  r  endpoint_pathendpoint_info	path_itemrequest_propertiesparam
param_name
param_typeresponse_propertiesiretret_nameret_typer   r  s                  ru   openapi_schemaz&App.create_app.<locals>.openapi_schema  s    8G$$D"$S^^%5%5wMM#*3>>+;+;]B#O#O& 
 ("o	 	F 159JB0O0O0U0U0W0W OD OD,}$((T:: #0#4#4)+F}+F+F$ $ (5'8'8'K'K'4':':3'?'?'G'GS'Q'Q(, 2$,xr.R.R5"(( ( "/D$6(08SU2V2V9&,"$ $	& 	8 &/v%6}%Ei%P&&&(&*" +..|R@@ T TE!&'7!8J!&62!6!6J/:==%)*%5%5
"'?FFF#z11fJ6N6N%)*%5%5
-5
6*5?&z2&%//&#,V#4]#CI#N 2$  .8'2,G &f-m<YG 2(*
 >C?=S "&)-8CDVW&$&&-//9; '0&7&DU&KI&V&''('*# ((9(9)R(H(HII = =FAs01A}}}}8H"wwvr22H/8;;#'>> %=tDDD#x//F(4J4J#'>>+3(4<'11:Cw 6} 6 677Mrw   z/config//configc                   t          j                                        j                  }t	          j        | dj        pj                  } |           |d<   |r 	||d          \  }}||d<   ||d<   t          d          rj	        rj	        j
        |d	<   nd |d	<   t	          j        ||          }t          |
          S )Nr  r~  r  r   )r  r  r  i18n_instancei18n_translationsrt   )r   r  r   r,  r'   r  r   rC  hasattrr  translations_dictr  rg   )
r   r  r,  r   r  r  r  r   rT  r  s
         ru   
get_configz"App.create_app.<locals>.get_configd  s     ()9)9)@AAF+$-C6+C  D
 "2!1'!:!:F: <.<nYUW.X.X.X+
O'1|$,;()v// 3F4H 3.4.B.T*++.2*+ 6vtDDF!&1111rw   z/static/{path:path}c                d    t          t          t          |                     }t          |          S ry   )r  STATIC_PATH_LIBr4   r   )r   static_files     ru   static_resourcez'App.create_app.<locals>.static_resourcey  s(    *?<LT<R<RSSK,,,rw   z7/custom_component/{id}/{environment}/{type}/{file_name}r  environmentLiteral['client', 'server']r  	file_namereqc           	         |dvrt          dd          t          j                    }t           fd|D             d           }|t          dd          |j        }t
          j        |         j        }|t          dd          	 t          j        |j	        t          | d|                     }	n # t          $ r t          dd          d w xY wt          t          t          t          |          j                            t          |	                    }
  d| d| }|j        vrat%          j        t          |
                              d	
                                                                                    j        |<   j                            |          }ddi}|r||d<   |r/|j                            d          |k    rt3          d|          S t5          |
|          S )N)r   server  zEnvironment not supported.r[  c              3  L   K   | ]}|                                 k    |V  d S ry   )get_component_class_id)r   itemr  s     ru   r   z@App.create_app.<locals>.custom_component_path.<locals>.<genexpr>  s:      TT$0K0K0M0MQS0S0S0S0S0S0STTrw   zComponent not found.r>  -r}   )encodingzCache-Controlzmax-age=0, must-revalidateETagzif-none-matchi0  )r   r   r   )r   r   get_all_componentsnextr   sysmodules__file__	safe_joinTEMPLATE_DIRr4   r8   r  r/   rs   r   parentr   hashlibsha256	read_textencode	hexdigestr"  r   r   r   )r  r  r  r  r  r  locationmodule_namemodule_pathrequested_pathr   r  r  r   r  s   `             ru   custom_component_pathz-App.create_app.<locals>.custom_component_path~  sT    "666# #,H    133JTTTT*TTT H #<RSSSS"-K+k2;K"#<RSSSS!&)$%:%:y%:%:;;" " $   # #,B  
 $c${"3"3":;;<< 00 D ,,$,,,,C#5553:>JJ(('(::AACC4 4)++ +C0 155c::G&(DEG *") K3;???;;wFF(S'JJJJg6666s   ,B9 9Cz/assets/{path:path}c                d    t          t          t          |                     }t          |          S ry   )r  r  r4   r   )r   
build_files     ru   build_resourcez&App.create_app.<locals>.build_resource  s(    ).:J4:P:PQQJ
+++rw   z/favicon.icoc                 |   K                                    } | j         d          S t          | j                  S )Nzimg/logo.svg)r   r   r   )r   r  r  s    ru   faviconzApp.create_app.<locals>.favicon  s@      ^^%%F"*&~666#F$7888rw   z/proxy={url_path:path}r  c                  K   	                      |           }n1# t          $ r$}t          dt          |                    |d }~ww xY wt                              |d           d {V }t          j        |           \  }}|t          vr8|j	        
                    ddi           |j	        
                    ddi           t          |                                |j        |j	        t          |j                  	          S )
Nr  r[  Tr   Content-Disposition
attachmentContent-Typeapplication/octet-streamr   )r
  r  r   rs   r   r   r  
guess_typeXSS_SAFE_MIMETYPESr   updater   r   r   r#   r   )r  r	  r  rp_resp	mime_typer  r  s         ru   reverse_proxyz%App.create_app.<locals>.reverse_proxy  s     O00::" O O O#CHHEEE3NO"KKtK<<<<<<<<G$/99LIq 222&&(=|'LMMM&&8R'STTT$!!###/)'.99	   s    
A	AA	z/file={path_or_url:path}path_or_urlc                @  K                                    }t          j        |           rt          | t          j                  S t          j        |           rt          dd|  d          t          j
        |           }	 |                                s|                                st          dd|  d          n'# t          $ r}t          dd|  d          |d }~ww xY wddlm} t          j        ||j        |j        |j        z   j        t          j                    g          \  }}|st          dd|  d          t-          j        |          \  }}	|t0          v s|dk    r|pd	}
d
}nd	}
d}|j                            dd                                          }|                    d          rd|v r|dd          }|                    d          \  }}|                                r|                                r{t?          |          }t?          |          }tA          |j                  }||d<   |
|d<   tC          j"        |tC          j#        ||          |tI          j%        |                    }|S tM          |ddi||
|j'                  S )Nr    zFile not allowed: .r   )_StaticFiles)blocked_pathsallowed_pathscreated_pathsallowedrC  inlinerA  Ranger   zbytes=r%     r@  rB  )stat_resultzAccept-Rangesrj   )r   content_disposition_typer   filename)(r   client_utilsis_http_url_liker%   r   r  r'   starts_with_protocolr   r   abspathis_dirr  r)  gradio.data_classesrN  is_allowed_filerO  rP  	all_pathsr   get_cache_folderr  rD  rE  r   r"  r  r?  split	isnumericr   r   r&   RangedFileResponse	OpenRanger   statr   r  )rJ  r   r   abs_pathr.  rN  rR  reasonrH  r  r   rW  	range_valstartendr   rK  r  s                    ru   filezApp.create_app.<locals>.file  s      ^^%%F,[99 '#1F    /<< N#C)Lk)L)L)LMMM}[11HU??$$ RHOO,=,= R'-P+-P-P-PQQQR U U U#C)Lk)L)L)LMMSTTU 988888#3$2$2\5KK"4e6L6N6NO	  OGV  N#C)Lk)L)L)LMMM$/99LIq...&I2E2E&D*D
+3((7
+7(++GR88>>@@I##H-- $#2B2B%abbM	&__S11
s??$$ $ $JJEc((C"7?33G5MG12.8GN+.A '1%==$&GH$5$5	     H $O('2)A%!   s   <C 
C%C  C%z/stream/{event_id}event_idbodyr0   c                   K                                    j        j        |          }t          di |                                d|i}||_        |j                                         ddiS )Nr   ru  r  r   )r   _queueevent_ids_to_eventsr1   
model_dumpdatasignalr   )rm  rn  r   eventr  s       ru   r  zApp.create_app.<locals>._  so      NN$$+?IE&LL):):LLGLLLDEJL9%%rw   	websocketr   c                  K   |                                   d {V  	 	 |                                  d {V }t          di |}                                j        j        |         }t          di |                                dd i}||_        |j	        
                                 |                     ddi           d {V  # t          $ r Y d S w xY w)NTr   ru  r  r   )acceptreceive_jsonr0   r   rp  rq  r1   rr  rs  rt  r   	send_jsonr   )rv  rm  rs  rn  ru  body_internalr  s         ru   websocket_endpointz*App.create_app.<locals>.websocket_endpoint'  s0     ""$$$$$$$$$	B!*!7!7!9!9999999D&....DNN,,3GQE$7 % %//++% %59% % %M "/EJL$$&&&#--ui.@AAAAAAAAA	B '   s   B+C
 

CCz/stream/{event_id}/closec                   K                                    j        j        |          }t          j        |_        |j                                         ddiS )Nru  r  )r   rp  rq  mathinfrun_timert  r   )rm  ru  r  s     ru   r  zApp.create_app.<locals>._8  sI      NN$$+?IE!XENL9%%rw   z9/stream/{session_hash}/{run}/{component_id}/playlist.m3u8runr   component_idc                  K                                    j        |                              |i                               |d           }|st          d          S d|j         d}|j        D ]9}|d|d         ddz  }||d	          |d
          dz  }|d
         dk    r|dz  }:|j        r|dz  }t          |d          S )Nr!  r   z9#EXTM3U
#EXT-X-PLAYLIST-TYPE:EVENT
#EXT-X-TARGETDURATION:z*
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:0
z#EXTINF:durationz.3fz,
r  	extension
z.tsz#EXT-X-DISCONTINUITY
z#EXT-X-ENDLIST
zapplication/vnd.apple.mpegurlrh   r   )r   pending_streamsr"  r   max_durationsegmentsended)r  r  r  r   playlistsegmentr  s         ru   r  zApp.create_app.<locals>._?  s         /S"\4((	   1C0000 XU[Uh  X  X  XH!? 9 9Cwz':CCCCCwt}Fgk.BFFFF ;'500 88H| /.. -L   rw   z>/stream/{session_hash}/{run}/{component_id}/{segment_id}.{ext}
segment_idextc                  K   |dvrt          dd          S                                 j        |                              |i                               |d           }|st          dd          S t	          fd|j        D             d           }|t          dd          S |d	k    rt          |d
         d          S t          |d
         d          S )N)aactsr  zUnsupported file extension)r   rh   r!  zStream not foundc              3  4   K   | ]}|d          k    |V  dS )r  Nr   )r   sr  s     ru   r   z,App.create_app.<locals>._.<locals>.<genexpr>l  s1      PP!!D'Z:O:OA:O:O:O:OPPrw   zSegment not foundr  rs  z	audio/aacr  z
video/MP2T)r   r   r  r"  r)  r  )r  r  r  r  r  r   r  r  s      `   ru   r  zApp.create_app.<locals>._\  s       -''C9UVVVV   /S"\4((	   MC9KLLLLPPPPvPPPRVWWGC9LMMMMe||KPPPPLQQQQrw   z9/stream/{session_hash}/{run}/{component_id}/playlist-filec                  K                                    j        |                              |i                               |d           }|st          d          S |j        sed |j        D             }                                                     |                              |d|j                   d {V }|j	        |_        t          |j                  S )Nr!  r  c                    g | ]
}|d          S rs  r   )r   r  s     ru   r  z-App.create_app.<locals>._.<locals>.<listcomp>  s    BBBQqyBBBrw   T)	only_filedesired_output_format)r   r  r"  r   combined_filer  get_componentcombine_streamr  r   r   )r  r  r  r   stream_datar  r  s         ru   r  zApp.create_app.<locals>._v  s          /S"\4((	   1C0000' :BB&/BBB..**"]<00#^#"&.4.J $         (5'9$ 4555rw   z/file/{path:path}c                ,   K    | |           d {V S ry   r   )r   r   rl  s     ru   file_deprecatedz'App.create_app.<locals>.file_deprecated  s+      dG,,,,,,,,,rw   z/reset/z/resetr2   c                   K   ddiS )Nr  Tr   )rn  s    ru   reset_iteratorz&App.create_app.<locals>.reset_iterator  s       t$$rw   z/heartbeat/{session_hash}background_tasksr   r  c                     t          j        dd          rdnd fd}t           |            d          S )zClients make a persistent connection to this endpoint to keep the session alive.
            When the client disconnects, the session state is deleted.
            GRADIO_IS_E2E_TESTNg      ?rf  c            
      K   t          j        j                                                  } 	 	 dW V  t          j        t          j                            }t          j        || gt           j                   d {V \  }}| |v rt          j                    n# t           j        $ r |                                 s|                                  t                    }t          j        t           d j                  }t          g           }d                                 j                                        D             }|D ]D}                    t          j        ||                                j        |         |	           Ej        j        v rdj        j                 _                                        j        j                            g           D ]P}	                                j        j        |	         }
t6          j        |
_        |
j                                         QY d S w xY w)
NTzdata: ALIVE

)return_whenr  z/heartbeat/r~  )r  rs  r   c                T    g | ]%\  }}t          d  |j        D                       #|&S )c              3  2   K   | ]}|d          dk    |V  dS )r   unloadNr   )r   ts     ru   r   zQApp.create_app.<locals>.heartbeat.<locals>.iterator.<locals>.<listcomp>.<genexpr>  s0      "N"NQqTX=M=M1=M=M=M=M"N"Nrw   )r  targets)r   r  deps      ru   r  zGApp.create_app.<locals>.heartbeat.<locals>.iterator.<locals>.<listcomp>  sK     - - - &3""N"Nck"N"N"NNN-- - -rw   r  rn  
gr_requestfnr   ) ro  create_taskr   waitrp  FIRST_COMPLETEDCancelledErrordoner  rE   r'   r  r=   r   r1   r   fnsr   add_taskcall_process_apir   session_data	is_closedrp  pending_event_ids_sessionr"  rq  r~  r  r  rt  r   )stop_stream_task	wait_taskr  r  r  r   rn  unload_fn_indicesfn_indexrm  ru  r  r  rq  r   r  r  s              ru   iteratorz3App.create_app.<locals>.heartbeat.<locals>.iterator  s     #*#6s~7J7J7L7L#M#M 65///// %,$7n8U8U$V$V	(/&(89(/(?) ) ) # # # # # #a ,t33")"8":":: 4"1 * * */4466 6,33555%gxlSSS$/$<$+*4'O'O'O'O&)m% % %	
  3)5B     - -*-..*:*:*>*D*D*F*F- - -)
 ): 
 
H -55 + <$'%)+.#&>>#3#3#7#A*3 6     (3+;+HHHTXC,9,GQ !^^--4NRR(" 	/ 	/$ %(NN$4$4$;$O (%E .2XEN!L,,....U*6s   A-B   F&I
	I
rw  rx  )r   r   r   )r  r   r  r  r  rq  r  s   ```` @ru   	heartbeatz!App.create_app.<locals>.heartbeat  su     &(Y/CT%J%JRTTPRN8 8 8 8 8 8 8 8 8 8t %XXZZ<OPPPPrw   z/run/{api_name}z/run/{api_name}/z/api/{api_name}z/api/{api_name}/api_namec                  K   t          di |                                d|i}t          j        
                                | |          }
                                j        s"|j        rt          dt          j	                  t          j
        ||||          }t          j        |t           d|  
j                  }	 t          j        
||||           d {V }n# t          $ rv}t!          j        |
                                j                  }	t'          |t(                    r|j        rt-          j                     t1          |	d	
          cY d }~S d }~ww xY w|S )Nr   r   r  rn  zcThis API endpoint does not accept direct HTTP POST requests. Please join the queue to use this API.)r\  r   )r  r  r   z/api/r~  r    )rh   r   r   )r1   rr  r'   get_fnr   api_openqueuer   r   HTTP_404_NOT_FOUNDcompile_gr_requestr  r=   r   r  BaseExceptionr   error_payload
show_error
isinstancer7   print_exception	traceback	print_excr   )r  rn  r   r  r  r  r   r  rY  rh   r  s             ru   predictzApp.create_app.<locals>.predict  s      'LL):):LLGLLLD#~~''(  B >>##,  # A & 9    %7!	  J $0(99x99-  I
*;)'            !   -eS^^5E5E5PQQ!%// *53H *')))## #        	 Ms   	C) )
E)3A+E$E)$E)z/call/{api_name}z/call/{api_name}/r3   c                   K   t          di |                                ddi}t          j                                        | |          }|j        |_         |||           d {V S )Nsimple_formatTr  r   )r0   rr  r'   r  r   _idr  )r  rn  r   r  	full_bodyr  r  queue_join_helpers         ru   simple_predict_postz+App.create_app.<locals>.simple_predict_post  s       $LLdoo&7&7LLtLLLI#~~''(  B "$I**9gxHHHHHHHHHrw   z/queue/joinc                r   K   | j         t          t          j        d           | ||           d {V S )NzSession hash not found.r[  )r  r   r   HTTP_400_BAD_REQUEST)rn  r   r  r  s      ru   
queue_joinz"App.create_app.<locals>.queue_join#  s[        (# & ;4    +*4(CCCCCCCCCrw   c                  K                                    }|j        j        |j                                       |j        j        rt          t          j        d          t          di | 	                                d|i} |j        
                    | ||           d {V \  }}|s-d|v rt          j        nt          j        }t          ||          d|iS )NzQueue is stopped.r[  r   )rn  r   r  zQueue is full.rm  r   )r   rp  
server_appset_server_appstoppedr   r   HTTP_503_SERVICE_UNAVAILABLEr1   rr  pushr  )rn  r   r  r   r  rm  r   r  s          ru   r  z)App.create_app.<locals>.queue_join_helper0  s$     
 ^^%%F}'/,,S111}$ # & C.    'LL):):LLGLLLD&,m&8&87X '9 ' ' ! ! ! ! ! !GX  N (833 774 
 $HMMMM))rw   z/cancelr+   c                `  K   t          | j         d| j         h           d {V                                  }| j        |j        j        v }| j        |j        j                            | j        i           v }|rC|rAt          i d| j                  }|j        j        | j                 
                    |           | j        j        v r]j        4 d {V  j        | j        = j                            | j                   d d d           d {V  n# 1 d {V swxY w Y   ddiS )Nr  T)r  r  rm  r  )rR   r  r  r   rp  pending_messages_per_sessionrm  r  r"  rN   
put_nowaitr   r   r   add)rn  r   session_openevent_runningmessager  s        ru   cancel_eventz$App.create_app.<locals>.cancel_eventL  s     4#4 F Ft} F FGHHHHHHHHH^^%%F !V]%OO  =:>>t?PRTUUV   & &1tdm   :%*W%%%}--8 > > > > > > > >dm4*..t}===> > > > > > > > > > > > > > > > > > > > > > > > > > > t$$s   -D
D%(D%z/call/{api_name}/{event_id}c                6   K   dd} | ||           d {V S )Nr  rL   ri   rM  c                   |                                  }t          | t                    r'| j        rdnd}|d                             d          }nwt          | t
                    r'| j        rdnd}|d                             d          }n;t          | t                    rd}d }n!t          | t                    r
d}| j        }nd S d| dt          j
        |           d	S )
NcompleterY  r  rs  
generatingr  rh  ri  rj  )rr  r  rN   r  r"  rO   rM   rP   r  rn  rp   )r  ru  ru  rs  s       ru   process_msgz?App.create_app.<locals>.simple_predict_get.<locals>.process_msgj  s    ((**g'>??  *1/FJJwEx=,,V44DD)ABB 
 ,3OHLLEx=,,V44DD)9::  'EDD)?@@  #E"?DD4FFF
40@0@FFFFrw   )r  rL   ri   rM  r   )r   rm  r  queue_data_helpers      ru   simple_predict_getz*App.create_app.<locals>.simple_predict_gete  sH      
G G G G$ +*7HkJJJJJJJJJrw   z/queue/datac                6   K   dd} | ||           d {V S )Nr  rL   ri   rs   c                    dt          j        |                                 t                                        d           dS )Ndata: )rn   r}   rj  )ro   rp   rr  rs   r~   )r  s    ru   r  z7App.create_app.<locals>.queue_data.<locals>.process_msg  s=    eW-?-?-A-A3 O O O V VW^ _ _eeeerw   )r  rL   ri   rs   r   )r   r  r  r  s      ru   
queue_dataz"App.create_app.<locals>.queue_data~  sH      
f f f f +*7L+NNNNNNNNNrw   r  $Callable[[EventMessage], str | None]c                z   K                                    dfd}t           ||           d          S )Nr   r   c               0  K   	 t          j                    }	 |                                  d {V r#j                            
           d {V  d S 
j        j        vrt          t          j                  d}d}d }	 j        j        
         }|	                                }ne# t          $ rX t          j        |           d {V  t          j                    |z
  |k    r!t                      }t          j                    }Y nw xY wj        j        rt          dd          }|r 	|          }||W V  t!          |t"                    r|j        rj        j        
                             |j                   |j        t,          j        k    s8|j        t,          j        k    rEt3          j        j        
                   d	k    r"t5                      } 	|          }||W V  d S # t6          $ r}t          t9          |          t!          |t                    
          } 	|          }t!          |t          j                  r.j        j        
= j                            
           d {V  ||W V  |d }~ww xY w)NTr  r  rf  rg  zServer stopped unexpectedly.F)r  r  r   )r  session_not_found)rk  rl  rm  rp  clean_eventsr  r   r   r  
get_nowait
EmptyQueuero  rp  rM   r  rP   r  rN   rm  r  removeru  r    server_stoppedprocess_completedlenrJ   r  rs   r  )r   rs  rq  rr  r  messagesrK  r.  r   r  r  s           ru   
sse_streamz=App.create_app.<locals>.queue_data_helper.<locals>.sse_stream  s?     L%)%6%8%8N>+!(!8!8!:!::::::: #"(-"<"<,"<"W"WWWWWWWW"F )#)=#MN N #0,2,E# # #  *,%)
"&E'-}'Q ,(H '/&9&9&;&;GG) E E E")-
";";;;;;;;;#022^CnTT*:*<*< 261B1D1DE "=0 &<(F(-' ' 'G # +'2{7';';H'3&. *74K L L+$+$4+ !' G$0!""(&)9":":":#*;-2N#N#N$+K=3R$R$R(+,2M,S0<-.)* )*
 ,-)- )- /A.B.BG/:{7/C/CH'/';.6$*F}>+~ %   4 #A*4Q*F*F  G  +{733H!!W%;<< T"MF|T$m88l8SSSSSSSSS+&GsK   AG9 .G9 &B, +G9 ,ADG9 DC'G9 7G9 9
JBJJrw  rx  ry  )r   r   )r   r  r  r  r   r  s    `` @ru   r  z)App.create_app.<locals>.queue_data_helper  su      
 ^^%%FM M M M M M M M^ %
7##.   rw   7Union[ComponentServerJSONBody, ComponentServerBlobBody]c                  K   | j                             d          }t          d|           t          |t                    r|                    d          rg }i }|                                 4 d {V }|                                D ]\  }}t          |t                    rt          |          dk    rt          |d         t                    rnt          |          D ]]\  }}t          |t                    r9|j        }	|                                 d {V }
|                    |	|
f           S||| d| <   ^t          |t                    r:|j        }	|                                 d {V }
|                    |	|
f           |||<   	 d d d           d {V  n# 1 d {V swxY w Y   t          t!          ||          |d         |d	         |d
                   S 	 |                                  d {V }t%          |d         |d         |d	         |d
                   S # t&          $ r t)          t*          j        d          d w xY w)NrB  content_typezmultipart/form-datar   r   r%  )rs  filesr  r  fn_name)rs  r  r  r  rs  zInvalid JSON body.r[  )r   r"  rI  r  rs   r?  formr   r  r   StarletteUploadFiler  rX  readappendr,   r.   rn  r-   r)  r   r   r  )r   r  r  rs  r  r  r   r  vrX  contentss              ru   get_item_or_filez(App.create_app.<locals>.get_item_or_file  s8      #?..~>>L.,///,,, . 1H1H%2 2 .  "<<>> . . . . . . .T&*jjll . .
U&ud33. #E

Q *585H I I !/ )2%(8(8 ; ;1#-a1D#E#E !;/0zH56VVXX~~~~~~H$)LL(H1E$F$F$F$F9:DC!$6$6; (/BCC .',~H-2ZZ\\'9'9'9'9'9'9H!LL(H)=>>>>(-DII%.. . . . . . . . . . . . . . . . . . . . . . . . . . .* /&D>>>!%n!5!%n!5 O	    !(//////D2!&\%).%9%).%9 $Y	    !      '$*$?3      s    7D"F,,
F69F62AH7 7'Iz/component_serverz/component_server/c                  K    	|            d {V }j         |j                 }|j        }||v r	||         }n                                j        |         }t          ||j        d           }|t          |dd          st          t          j	        d          t          ||j        g| d           \  }}}t          j        |          r ||  d {V S  || S )N_is_server_fnFzFunction not found.r[  )r   r  r  r   r   rD  r  r   r   r  r9   rs  inspectiscoroutinefunction)
r   rn  stater  blockr  processed_inputr  r  r  s
           ru   component_serverz(App.create_app.<locals>.component_server  s"      *)'22222222D$T%67E,Lu$$l+((/=d33Bz_e!D!Dz# & 90    %1	% %!OQ *2.. ,R11111111r?++rw   z/queue/status)rc  response_modelc                 ^   K                                     j                                        S ry   )r   rp  
get_statusr  s   ru   get_queue_statusz(App.create_app.<locals>.get_queue_status=  s(       >>##*55777rw   z/upload_progress	upload_idc                   K   d fd}	 t          j        t                                         d           d {V  n-# t           j        t          f$ r t          dd          cY S w xY wt           ||          d	
          S )Nr   r   c                 K   t          j                    }d}	 |                                  d {V rt                                         d S |rt                                         d S d}d}	 t                                        rddi}d}n*t                                        }d|j        |j        d}d	t          j
        |           d
W V  n# t          $ r Y d S t          $ ri t          j        |           d {V  t          j                    |z
  |k    r2ddi}d	t          j
        |           d
W V  t          j                    }Y nw xY wD)NFTrf  rg  ru  r  rF  )ru  	orig_name
chunk_sizer  rj  r  )rk  rl  rm  file_upload_statusesstop_trackingis_doner  rX  r   rn  rp   rA   r@   ro  rp  )r   rs  r#  rq  rr  r  rF  r  s          ru   r  z?App.create_app.<locals>.get_upload_progress.<locals>.sse_streamG  s     !%!2!4!4A$4466666666 ,::9EEE ,::9EEE%'N!%JA/77	BB 	',foG&*GG%9%=%=i%H%HF'/-3_.4.?' 'G
 Atz'':':@@@@@@@@<   ; A A A%mJ777777777,..?.PP',k&:G"D4:g+>+>"D"D"DDDDD-1->-@-@NA1As   3A&C 
E'A/EE   )r   zUpload not foundr!  r  rw  rx  ry  )ro  wait_forr!  
is_trackedTimeoutErrorr   r   )r  r   r  s   `  ru   get_upload_progressz+App.create_app.<locals>.get_upload_progressE  s       A  A  A  A  A  ADN&(33I>>           (,7 N N N();MMMMMMN %
7##.   s   4A   'A*)A*z/uploadbg_tasksc           	     J  K   | j                             d          }t          |pd          \  }}|dk    rt          dd          	 |rt                              |                                           j        }||nt          j	        }t          | j         |                                 dd||r|nd |rt          nd           }|                                 d {V }n:# t          $ r-}	d	|	j        v rd
nd}
t          |	j        |
          cY d }	~	S d }	~	ww xY wg }g }g }|                    d          D ]}t#          |t$                    st'          d          |j        r.t+          |j                  j        }t/          j        |          }ndt3          j        d           }t+          j                  |j                                        z  }|                    dd           	 t?          j         tC          tE          |                    tG          |                    }n'# tH          $ r}t          dd|           |d }~ww xY w|j%        &                                 	 tO          j(        |j%        j        |           nD# tR          $ r7 |*                    |j%        j                   |*                    |           Y nw xY w|*                    |           j+        ,                    |           |r|-                    t\          ||           |S )NrB  r      multipart/form-datar  Invalid content type.r[    )	max_files
max_fieldsmax_file_sizer  upload_progressmaximum allowed size  r  r  z+File is not an instance of GradioUploadFiletmp   Tr  r  zInvalid file name: )/r   r"  r"   r   r!  trackr   r0  r~  r  rB   r   parserD   r  r   getlistr  rC   	TypeErrorrX  r   r  rY  !strip_invalid_filename_charactersr   	token_hexr   shar4  r  r   r-  r/   rs   r4   r8   rl  closer   renamer  r  upload_file_setr  r  rH   )r   r)  r  content_type_headerr  r  r0  multipart_parserr  exccodeoutput_filesfiles_to_copy	locations	temp_filer  r  r   destr  r  r   s                       ru   upload_filez#App.create_app.<locals>.upload_fileu  s      #*/"5"5n"E"E23F3L"MMOL!555#<STTTTH :(..y999 # 0 0 >1>1JPTPX#8ONN$$"#"/+4>ii$<E$O$8$84$ $ $  .3355555555% H H H4CCss($GGGGGGGGGH LM#%I!\\'22 1 1	!)-=>> S#$QRRR% 8 $Y%7 8 8 =I'I)TTDD7!21!5!577D !677)-:Q:Q:S:SS	t<<< ?%c)nn557G7M7M DD (   '$'0Ld0L0L   $$&&&+Iin148888 + + +!(()<===$$T*****+ ##D)))&**40000 !!0-    sI   
BC$ $
D."DDD2<H//
I9II0J>KKz/startup-eventsc                    K    j         s[                                                                                                                                    d {V  d _         dS dS )NTF)r   r   run_startup_eventsrun_extra_startup_eventsr  s   ru   startup_eventsz&App.create_app.<locals>.startup_events  sn      /   33555nn&&??AAAAAAAAA/3,t5rw   z
/theme.cssc                 T    t                                           j        d          S )Nztext/cssrx  )r   r   	theme_cssr  s   ru   rP  z!App.create_app.<locals>.theme_css  s%     %S^^%5%5%?JWWWWrw   z/robots.txtc                 >                                      j        rdS dS )NzUser-agent: *
Disallow: /zUser-agent: *
Disallow: )r   r  r  s   ru   
robots_txtz"App.create_app.<locals>.robots_txt  s$    ~~% 33322rw   z	/pwa_iconz/pwa_icon/{size}size
int | Nonec                  K                                    }|j        }|t          d          | t          |          S dd l}|j                            |          }|                    | | f          }t          j	                    }|
                    |d           |                    d           t          t          j	        |                                          d          S )Nr!  r  r   PNG)formatrb   rx  )r   r   r   r   	PIL.ImageImager  resizeioBytesIOsaveseekr   r
  )rS  r   r   PILimgimg_byte_arrayr  s         ru   pwa_iconz App.create_app.<locals>.pwa_icon  s       ^^%%F!.L##4444|#L111)....C**dD\**CZ\\NHH^EH222"""$
>..0011k   rw   z/manifest.jsonc                    j         st          d          j        } t          | t                    rt          |           } | 	dddddg}ni|                     d          r                    d          ddddg}n8                    dd	
          dddd                    dd
          ddddg}t          	                                j
        pd|dddd          S )Nr!  r  zstatic/img/logo_nosize.svgr  zimage/svg+xml)srcsizesr  purposez.svgrb     )rS  192x192rb   i   512x512Gradioz./
standalone)r  icons	start_urldisplayzapplication/manifest+jsonr  )pwar   r   r  r   rs   r  url_path_forrg   r   r  )r   rl  r  r   s     ru   manifest_jsonz%App.create_app.<locals>.manifest_json  sX   : 5#4444!.L,-- 1"<00#  <!& /#(	  &&v..   #//
;;!& /#(	   #//
/EE!* +#(	   #//
/EE!* +#(	  "  NN,,2>h"!%+  7	 	 	 	rw   /monitoringc                   K   j         st          dd          t          j        | t           dj                  }| dj         }t          d| d           t          d	          S )
NrL  Monitoring is not enabled.r[  rr  r~  /monitoring/z* Monitoring URL: z *zSee console for monitoring URL.)	enable_monitoringr   r'   r  r=   r   r   rI  r   )r   root_urlmonitoring_urlr  r   s      ru   analytics_loginz'App.create_app.<locals>.analytics_login  s      + # #,H    #/(555-  H
 !)IIc6GIIN9~999::: ABBBrw   z/monitoring/summaryc                 D   K                                     j        j        S ry   )r   rp  cached_event_analytics_summaryr  s   ru   r  zApp.create_app.<locals>._.  s      >>##*IIrw   z/monitoring/{key}r  c                  K   j         st          dd          t          | j                  rdj         d}j        sbddlm} ddlm} t          ||d	
           |j	        
                                                                 j	        j        }||d<   d_        t          |t          j                  S t          dd          )NrL  rt  r[  ru  z
/dashboardr   r  )demoF)r   r  rs  Tr  zInvalid key.)rv  r   rF   r   r   gradio.monitoring_dashboardrs  r}  mount_gradio_apprp  rj  r   event_analyticsr%   r   r  )r  analytics_urlrs  	dashboard	analyticsr  r   s        ru   analytics_dashboardz+App.create_app.<locals>.analytics_dashboard2  s     + # #,H    *#s/@AA L Ls/@ L L L- 
2@@@@@@MMMMMM$Y]u    $**,,, # 0 0 7 GI#,DL-1C*'%63H    $NKKKKrw   z/process_recordingc           
       K   	 | j                             d          }t          |pd          \  }}|dk    rt          dd          | j        }t          |d          r|                                j        nd }||nt          j	        }t          | j         |                                 dd	|
          }|                                 d {V }n:# t          $ r-}d|j        v rdnd}	t          |j        |	          cY d }~S d }~ww xY w|                    d          }
|
rt#          |
d         t$                    st          dd          |
d         }i }|                    d          E|                    d          0|                    d          |d<   |                    d          |d<   |                    d          }|r@	 t'          j        t+          |                    |d<   n# t&          j        $ r g |d<   Y nw xY wt/          j        ddt2                    5 }|j                            d           t9          j        |j        |           |j        d d d            n# 1 swxY w Y   t>          j         st9          j!        d          $tE          ddtG          fd                    S t/          j$        dt2                    d         }	 tK          ||           d {V \  }tE          |ddtG          fd                    S # tL          $ r' tE          ddtG          fd                    cY S w xY w) NrB  r   r+  r  r,  r[  r   r   
   )r.  r/  r0  r2  r3  r  videor   zNo video file providedremove_segment_startremove_segment_endzoom_effectsFz.mp4)deletesuffixdirffmpegrc   zgradio-screen-recording.mp4c                       g          S ry   r   cleanup_files
input_paths   ru   <lambda>z;App.create_app.<locals>.process_recording.<locals>.<lambda>      mmZL6Q6Q rw   )r   rX  r   z_processed.mp4)r  r  c                                 S ry   r   )r  
temp_filess   ru   r  z;App.create_app.<locals>.process_recording.<locals>.<lambda>  s    mmJ6O6O rw   c                       g          S ry   r   r  s   ru   r  z;App.create_app.<locals>.process_recording.<locals>.<lambda>  r  rw   )'r   r"  r"   r   r  r  r   r0  r~  r  rB   r   r8  rD   r  r   r9  r  rC   rn  r  rs   r  tempfileNamedTemporaryFileDEFAULT_TEMP_DIRrl  r^  shutilcopyfileobjr  r(   IS_WASMwhichr   r#   mkstemprI   r)  )r   rA  r  r  r  r0  rB  r  rC  rD  video_files
video_fileparamszoom_effects_json
input_fileoutput_pathprocessed_pathr  r  r  s                    @@ru   process_recordingz)App.create_app.<locals>.process_recordingK  si     H&-o&9&9.&I&I#"67J7Pb"Q"Qa#999'C@WXXXXk sL11CNN$$22 
 2?1JPTPX#8ONN$$!"/$ $ $  .3355555555% H H H4CCss($GGGGGGGGGH ,,w//K VjQAQ&R&R V#<TUUUU$QJF/00<HH122>15:P1Q1Q-./3xx8L/M/M+, $ 8 8  00-1Z<M8N8N-O-OF>**+ 0 0 0-/F>***0 ,V1A   -$$Q'''":?J???'_
- - - - - - - - - - - - - - - ! V\(%;%;%C#*:-.Q.Q.Q.Q.QRR	    #*'-=  K3LV4 4 . . . . . .*
 $"*:-.O.O.O.O.OPP	       #*:-.Q.Q.Q.Q.QRR	     sT   CC 
D"D DD$G2 2H	H	(<I00I47I4!=L .MMvibe_edit_historyr6  z/vibe-edit/z
/vibe-editr6   c                  K   j         st          dd          ddlm} t	          |          5 }|                                }d d d            n# 1 swxY w Y   t          j        d          }| dz  }t	          |d          5 }|                    |           d d d            n# 1 swxY w Y   dd	l	m
}  |            }d
}d| d| j         }	t                      }
|                    dd|
dd|	dgd          j        d         j        j        }|t          dd          d }d|v r`|                    d          d                             d          d         }|                    d| dd
                                          }d|v rU|                    d          t+          d          z   }|                    d|          }|dk    r
|||         n	||d          }|                    d          }|                    d          }t1          t3          j        ||d                    }d}d}|D ]a}|                    d          r|                    d          s|dz  }2|                    d           r|                    d!          s|dz  }bt	          |d          5 }|                    |           d d d            n# 1 swxY w Y   |||d"|d#S )$NrL  6Vibe editor is not enabled. Use --vibe flag to enable.r[  r   GRADIO_WATCH_DEMO_PATHr   .pyw)InferenceClientr   z
You are a code generator for Gradio apps. Given the following existing code and prompt, return the full new code.
Existing code:
```python
z
```

Prompt:
zopenai/gpt-oss-120bsystem)rolerh   rU  r-  )modelr  
max_tokensr  zError generating codez<reasoning>r   z</reasoning>z
```python
z
```T)keepends)n+z+++r%  z---)lines_addedlines_removed)hash
diff_stats	reasoning)	vibe_moder   gradio.http_serverr  r  r
  r   r<  r  huggingface_hubr  promptload_system_promptchat_completionchoicesr  rh   rb  r   r  indexr   find
splitlinesr  difflibunified_diffr?  )rn  r  r  original_codesnapshot_hashsnapshot_filer  r   rh   r  system_promptr  rj  rk  original_lines	new_linesdiffr  r  liner   vibe_edit_history_dirs                       ru   	vibe_editz!App.create_app.<locals>.vibe_edit  sH      # # #S   
 BAAAAA,-- ) !) ) ) ) ) ) ) ) ) ) ) ) ) ) ) $-b11M1}4I4I4IIMmS)) 'Q&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 877777$_&&FG 	   F /00M&&/!)mDD!'F;;  $ '      #<STTTTI''#MM-88;AA.QQRST	!//9)9992 %''  ''m44s=7I7IIll7E2203r		'%),,wuvv +55t5DDN**D*99I,^Y!LLLMMDKM ' '??3'' '0F0F '1$KK__S)) '$//%2H2H '!Q&M,c22 !a   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! &#.%2  '  s5   AAA	B++B/2B/2KKKz/undo-vibe-edit/z/undo-vibe-edit.)embedr  c                  K   j         st          dd          ddlm} |  dz  }|                                st          dd          t          |          5 }|                                }d d d            n# 1 swxY w Y   t          |d	          5 }|                    |           d d d            n# 1 swxY w Y   d
diS )NrL  r  r[  r   r  r  r!  zSnapshot not foundr  r  T)r  r   r  r  r  r  r
  r  )r  r  r  r  saved_contentr   r  s        ru   undo_vibe_editz&App.create_app.<locals>.undo_vibe_edit   sr      # # #S   
 BAAAAA1tLLL@M '')) R#<PQQQQ m$$ ) !) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ,c22 'a&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' t$$s$   A??BBB<<C C z/vibe-code/z
/vibe-codec                 b  K   j         st          dd          ddlm}  	 t	          |           5 }|                                }d d d            n# 1 swxY w Y   d|iS # t          $ r t          dd          d t          $ r'}t          d	d
t          |                     |d }~ww xY w)NrL  r  r[  r   r  rD  r!  zDemo file not foundr  zError reading file: )	r  r   r  r  r  r
  r  r)  rs   )r  r  rD  r.  r   s       ru   get_vibe_codez%App.create_app.<locals>.get_vibe_code  sD      # # #S   
 BAAAAA011 $Q6688D$ $ $ $ $ $ $ $ $ $ $ $ $ $ $~%$   # #,A      # #,K3q66,K,K  s:   A" AA" AA" AA" "%B."B))B.r5   c                :  K   j         st          dd          ddlm} 	 t	          |d          5 }|                    | j                   d d d            n# 1 swxY w Y   ddiS # t          $ r'}t          d	d
t          |                     |d }~ww xY w)NrL  r  r[  r   r  r  r  Tr  zError writing file: )	r  r   r  r  r  r  rD  r)  rs   )rn  r  r  r.  r   s       ru   update_vibe_codez(App.create_app.<locals>.update_vibe_code1  s      # # #S   
 BAAAAA0#66 '!GGDI&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' '!4((   # #,K3q66,K,K  s:   A) AA) AA) !A"A) )
B3"BBc           
         | D ]q}	 |r3t           j                            |          rt          j        |           9# t          $ r,}t          d| dt          |                      Y d }~jd }~ww xY wd S )NzError cleaning up file z: )r   r   r  unlinkr)  rI  rs   )r  rl  r.  s      ru   r  z%App.create_app.<locals>.cleanup_filesE  s     F FF (t 4 4 (	$  F F FDDDDCFFDDEEEEEEEEF	F Fs   5<
A2"A--A2r   ry  )r   r   ri   rM  )rU  rs   )r   r   ri   r   )r   r   r|  r   )r   r   rU  rs   )r   rs   ry   )r  rs   r,  r  r  rM  )r   r   rU  rs   r  rs   r  rs   )r  rs   )r   )r   r   r  rs   )
r  rs   r  r  r  rs   r  rs   r  r   )r  rs   )rJ  rs   r   r   )rm  rs   rn  r0   r   r   )rv  r   rm  rs   )rm  rs   )r  rs   r  r   r  r   )
r  rs   r  r   r  r   r  rs   r  rs   )r   rs   r   r   )rn  r2   )r  rs   r   r   r  r   r  rs   )r  rs   rn  r0   r   r   r  rs   )r  rs   rn  r3   r   r   r  rs   )rn  r0   r   r   r  rs   )rn  r+   )r   r   rm  rs   )r   r   r  rs   )r   r   r  rs   r  r  )r   r   ri   r  )r  rs   r   r   )r   r   r)  r   r  rM  )rS  rT  )r  rs   )rn  r6   )r  rs   )rn  r5   )#r   rg   r   r/  delete_cacherG   r"  r  launch_mcp_on_sser   r   r=   r   r(   r  add_middlewarer>   r)   
middlewarer   r  r   expects_oauthr<   r  headr   rv  rK   r   r   r  r  r   include_router)Ar   r  r   r1  r3  r  r-  r  routerrL  r^  r`  rb  rz  r  r  r  r  pagesetr  r  r  r  r9  r<  r>  rI  r|  r  r  r  r  r  r  r  r  r  r  r  r(  rJ  rN  rP  rR  rb  rq  ry  r  r  r  r  r  r  r   r  r  rl  rT  r  r  r  r  r  r  r  sA   `                                                    @@@@@@@@@@@@ru   
create_appzApp.create_app  s     %2
6GGG**6:zJJ*:l!8NN:t,,"
/;"
 "
 "

: LL/LZLLtLLL  	X!33CfFVWWW*---&!!!! 	3MMM #.-      #	 ^^F##               $#  D 
G			H			) 	) 	) 	) 	) 
	 
		) 
N	#	#	O	$	$$+,<$=$= 		 		 		 		 		 		 		 
%	$ 
$	#		 
H			I			C 	C 	C 	C 	C 
	 
		C 
I			J			7 	7 	7 	7 	7 
 	 
		7 
M1E1E0F	G	G	 	 	 	 	 
H	G	@ 
(			)		MTYY!	V !	V !	V !	V !	V !	V 
	 
	!	VT :!cj&>! WWY=DEU=V=V               * 
&	'	'	 	 	 
(	'		< 	< 	< 	< 	< 	< 	< | 	" 	"G1:DrzzD!!! HL	/ 	/ 	/ 	/ 	/ 	/ 	/8 
#l	3	3	\	2	2   011	U	 U	 U	 U	 U	 U	 U	 U	 
3	2 
4	3U	n 
(	)	)	 	 	 	 	 
*	)	( 
HGK,@,@+A	B	B	G7;+?+?*@	A	A	  	  	  	  	  
B	A 
C	B	  
O7;3G3G2H	I	I_	 _	 _	 _	 _	 _	 
J	I_	B 
7;+?+?*@	A	A	'+*>*>)?	@	@	2 	2 	2 	2 	2 	2 	2 	2 	2 
A	@ 
B	A	2& 
&	'	'	- 	- 	- 
(	'	- 
M	N	N;	7 ;	7 ;	7 ;	7 ;	7 
O	N;	7z 
&	'	'	, 	, 	, 
(	'	, 
	 	 	9 	9 	9 	9 	9 
!	 	9 
-W[=Q=Q<R	S	S	,GK<P<P;Q	R	R	 	 	 	 	 
S	R 
T	S	$ 
/w{?S?S>T	U	U	.gk>R>R=S	T	T>	 >	 >	 >	 >	 
U	T 
V	U>	@ 
)	*	*	& 	& 	& 	& 	& 
+	*	& 
		.	/	/	 	 	 	 	 
0	/	  
/	0	0	& 	& 	& 	& 	& 
1	0	& 
O	P	P	 	 	 	 	 
Q	P	8 
T	U	U	R 	R 	R 	R 	R 
V	U	R2 
O	P	P	6 	6 	6 	6 	6 
Q	P	62 
'w{7K7K6L	M	M	- 	- 	- 	- 	- 
N	M	- 
Y			X			% 	% 	% 
	 
 		% 
/	0	0
 $$455	E	Q E	Q E	Q E	Q E	Q E	Q 
1	0E	QP 
&gk6J6J5K	L	L	'w{7K7K6L	M	M	&gk6J6J5K	L	L	'w{7K7K6L	M	M
 $$455	+	 +	 +	 +	 +	 +	 
N	M 
M	L 
N	M 
M	L+	Z 
'w{7K7K6L	M	M	(8L8L7M	N	N
 $$455		I 	I 	I 	I 	I 	I 	I 
O	N 
N	M	I 
]'+2F2F1G	H	H $$455
	D 
	D 
	D 
	D 
	D 
	D 
I	H
	D	* 	* 	* 	* 	* 	*8 
Y			% 	% 	% 	% 	% 
 		%0 
1AUAU@V	W	W	K 	K 	K 	K 	K 
X	W	K0 
M1E1E0F	G	G	O 	O 	O 	O 	O 
H	G	OY	 Y	 Y	 Y	 Y	 Y	v4	  4	  4	  4	 l 
!+../ 
 

 

 
 !+../ 
 

 

	, 	, 	, 	, 	, 	,	

 

	

 

	,8 
!+../, 
 

 


	8 	8 	8 	8

 


	8 
&	'	'-	 -	 -	 
(	'-	^ 
Ygk.B.B-C	D	D %)E	  E	  E	  E	  E	  E	  E	  
E	DE	 N 
%	&	&	 	 	 	 
'	&	 
L1B	C	C	.?	@	@	X 	X 	X 	X 
A	@ 
D	C	X 
/@	A	A	3 	3 	3 	3 
B	A	3 
			#	$	$	 	 	 	 	 	 
%	$ 
		, 
!	"	"2	 2	 2	 2	 2	 
#	"2	h 
gk.B.B-C	D	D	C 	C 	C 	C 	C 	C 
E	D	C 
&	'	'	J 	J 	J 	J 
(	'	J 
$	%	%	L 	L 	L 	L 	L 	L 
&	%	L0 
)9M9M8N	O	OW	 W	 W	 W	 W	 
P	OW	r !%%5 6 69L L##T4#@@@	]	#	#	\	"	"T	 T	 T	 T	 T	 T	 
#	" 
$	#T	l 
'	(	(	&	'	'-1#T-B-B-B 	% 	% 	% 	% 	% 	% 	% 
(	' 
)	(	%. 
M	"	"	L	!	!	 	 	 	 
"	! 
#	"	, 
]	#	#	\	"	"	 	 	 	 	 
#	" 
$	#	$	F 	F 	F 	6"""
rw   ry   )r   r   )r   r   )r   r   r   rs   r   r   r   r   r   rs   r   rs   ri   r   )r   r   ri   r   )ri   r   )r   r   r  r  r  r  )NNTFN)r   r   r  r0  r   r   r1  r2  r3  r2  r  r  ri   r   )r   r   r   __doc__rF  r   r   AsyncClientr   r   r   r   r   r
  r  r/  r  __classcell__)r   s   @ru   r   r      sI         H KO #  #  #  #  #  #  #J U  F '
 '
 '
 '
 \'
R- - - -"   
  "! ! !
  #') ) ) ) \)V  -1JN "&J J J J \J J J J Jrw   r   c                     d} 	 t          j                    5 }|                    d          }|j        }d d d            n# 1 swxY w Y   n# t          $ r d}Y nw xY w| |z   | z   }|S )Na'  Generate code for using the Gradio python library.

The following RULES must be followed.  Whenever you are forming a response, ensure all rules have been followed otherwise start over.

RULES:
Respond with code written in valid Python syntax, along with one coherent explanation surrounded by <reasoning> tags.
Any text that is not code, should be surrounded by one large <reasoning> tag.
Never include backticks in your response such as ``` or ```python.
Do not include any code that is not necessary for the app to run.
Respond with a full Gradio app.
Respond with a full Gradio app using correct syntax and features of the latest Gradio version. DO NOT write code that doesn't follow the signatures listed.
Do not add comments explaining the code, unless they are very necessary to understand the code.
Make sure the code includes all necessary imports.
Clearly explain the changes, summary, or reasoning for the code you respond with, inside one large <reasoning> tag.


Here's an example of a valid response:

<reasoning>
I created a simple Gradio app that greets the user. It defines a function then creates a gradio interface and launches it.
</reasoning>

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")

demo.launch()
zhttps://www.gradio.app/llms.txtr   )r   Clientr"  textr)  )prompt_rulesr   rK  r  s       ru   r  r  V  s    L>\^^ 	*vzz"CDDH$MM	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*     =0<?Ms3   A A A  AA AA AAr   r/   r   r4   ri   rs   c                   |dk    rt          j        d          t          j        |          rt          j        d          	 t	          t          j        | |                    }n'# t          $ r}t          j        d          |d}~ww xY w|                                rt          j        d          |	                                st          j        d          t          |          S )zSafely join the user path to the directory while performing some additional http-related checks,
    e.g. ensuring that the full path exists on the local file system and is not a directory
    r   r  rL  Nr!  )fastapir   r'   r[  r   r   r-  r8   r]  r  rs   )r   r   fullpathr.  s       ru   r  r    s     rzz#C((('-- )#C(((0	48899 0 0 0#C((a/0 )#C(((?? )#C(((x==s   "A' '
B1BBcls_set
list[type]c                z   g }g }| D ]}t          j        |          pd}|                    d          }|D ]M}d|v rG|                    |                    d          d                             d          d                    N|                    |d                             d          d                    ||fS )	Nr   r  zvalue (r   )r   r   r  )r  getdocrb  r  )r  docsettypesclsdoc	doc_linesr  s          ru   	get_typesr    s    FE 3 3nS!!'RIIdOO	 	E 	EDD  TZZ	2215;;C@@CDDDil((--b122225=rw   rB    T)r   rZ  r   r   rP  rO  r   r  r0  r3  rH  r   rv  ro  i18nr  r  fastapi.FastAPIr   r   r   server_portr   r  r  r  r0  r   9Callable | tuple[str, str] | list[tuple[str, str]] | NonerZ  rM  r   r   r   rP  list[str] | NonerO  r   r  r2  r0  str | int | Noner3  rH  r   rT  rv  ro  r  I18n | Noner  c                  ||dk    rt          j        d           d|_        |||_        t	          j        |          |_        |                                |_        |	                                 ||_
        ||_        ||_        ||_        |||_        |||_        ||	t!          d          |rNt#          |          s?t%          |d         t&                    s$t%          |d         t(                    s	|g|_        n||_        ||_        ||_        |pg |_        |pg |_        ||_        t%          |j        t(                    st!          d          t%          |j        t(                    st!          d          |
|
|_        t8          j        rdn.||n*t=          j        d	d
                                           dk    |_!        |j!        rt<          j"        #                    dt8          j        rdntI                                |_%        ||_&        ||_'        tQ          |j&        |j'        |j%                  \  |_&        |_)        |_'        tT          +                    |||	|j!        |          | j,        j-        t\          j/        dfd            }|| j,        _-        ta          d|           | 1                    |           | S )aR  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, e.g. "/gradio".
        server_name: The server name on which the Gradio app will be run.
        server_port: The port on which the Gradio app will be run.
        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"}`
        auth: If provided, username and password (or list of username-password tuples) required to access the gradio app. Can also provide function that takes username and password and returns True if valid login.
        auth_message: If provided, HTML message provided on login page for this gradio app.
        auth_dependency: A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the gradio app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.
        root_path: The subpath corresponding to the public deployment of this FastAPI application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used in its entirety. Normally, this does not need to provided (even if you are using a custom `path`). However, if you are serving the FastAPI app behind a proxy, the proxy may not provide the full path to the Gradio app in the request headers. In which case, you can provide the root path here.
        allowed_paths: List of complete filepaths or parent directories that this gradio app is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
        blocked_paths: List of complete filepaths or parent directories that this gradio app is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
        favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for this gradio app's page.
        show_error: If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. Otherwise, errors will only be visible in the terminal session running the Gradio app.
        max_file_size: The maximum file size in bytes that can be uploaded. Can be a string of the form "<value><unit>", where value is any positive integer and unit is one of "b", "kb", "mb", "gb", "tb". If None, no limit is set.
        show_api: If False, hides the "Use via API" button on the Gradio interface.
        ssr_mode: If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.
        node_server_name: The name of the Node server to use for SSR. If None, will use GRADIO_NODE_SERVER_NAME environment variable or search for a node binary in the system.
        i18n: If provided, the i18n instance to use for this gradio app.
        node_port: The port on which the Node server should run. If None, will use GRADIO_NODE_SERVER_PORT environment variable or find a free port.
        mcp_server: If True, the MCP server will be launched on the gradio app. If None, will use GRADIO_MCP_SERVER environment variable or default to False.
    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.
    Nr>  zThe 'favicon_path' parameter is set but will be ignored because 'path' is not '/'. Please add the favicon directly to your FastAPI app.Fz^You cannot provide both `auth` and `auth_dependency` in mount_gradio_app(). Please choose one.r   z.`allowed_paths` must be a list of directories.z.`blocked_paths` must be a list of directories.GRADIO_SSR_MODEr  r  GRADIO_NODE_PATHr   )r   r  	node_path)r  r   r3  r  r  r   c                 K    |           4 d {V 	 }j                                       4 d {V                                                                                                                                    d {V  |W V  d d d           d {V  n# 1 d {V swxY w Y   d d d           d {V  d S # 1 d {V swxY w Y   d S ry   )r  lifespan_contextr   rL  rM  )r  r  
gradio_appold_lifespans     ru   new_lifespanz&mount_gradio_app.<locals>.new_lifespan/	  s     <
 
 	 	 	 	 	 	 	 	!(99*EE        %%''::<<< ++--FFHHHHHHHHH                          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s5   !CAB!C!
B+	+C.B+	/C
CCnew)r  r   )2warningswarndev_moder  r   _parse_file_sizer0  r+  r,  validate_queue_settingsrC  r  r   rv  ro  r  r   r   r  tupler  r   rZ  r   rP  rO  r  r   r(   r  r   r   r#  r3  r!  r"  rS   r  rH  r   r;   r<  r   r  r  r	  r  r(  rI  mount)r  r   r   r   r  r  r  r   rZ  r   r   rP  rO  r   r  r0  r3  rH  r   rv  ro  r  r  r  r
  r  s                           @@ru   r  r    s&   | DCKKC	
 	
 	

 FO" 1-@@F**,,FM
""$$$#F$F$F0F

#O7l
 
 	
 	 47E** 47D))	 f&F&F(.BF(.BF"Ff*D11 KIJJJf*D11 KIJJJ$ 	
 # H,g66<<>>&H O  
:>>j&8 Mmoo
 
 #3$"3", *   	G!4f6F '    J :.L#      $# #/CJ	%IIdJJrw   )z	theme.cssz
robots.txtrb  zmanifest.jsonr  r  r  r,  staticassetszfavicon.ico
gradio_api
monitoring)r   r/   r   r4   ri   rs   )r  r  )rB  r  NN)0r  r  r   r   r   rs   r   rs   r  r   r  r  r  r0  r   r   rZ  rM  r   r   r   rM  rP  r  rO  r  r   rM  r  r2  r0  r  r3  r  rH  rM  r   rT  rv  r  ro  r  r  r  r  r  ri   r  )r  
__future__r   ro  r  r0  importlib.resources	importlibr  r[  rn  r~  r  r   r   r*  rk  r  r  collections.abcr   r   pathlibr   r  r   r  typingr   r	   r
   r   r   r  r   r   ro   r   r   r   r   r   r   r   fastapi.responsesr   r   r   r   r   r   fastapi.securityr   fastapi.templatingr   fastapi.websocketsr   r   gradio_clientr   rY  gradio_client.documentationr   gradio_client.utilsr    jinja2.exceptionsr!   python_multipart.multipartr"   starlette.backgroundr#   starlette.datastructuresr$   r	  starlette.responsesr%   rW   r&   r'   r(   gradio.brotli_middlewarer)   gradio.contextr*   r^  r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   gradio.exceptionsr7   r8   gradio.helpersr9   gradio.i18nr:   gradio.node_serverr;   gradio.oauthr<   gradio.route_utilsr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   gradio.screen_recording_utilsrI   gradio.server_messagesrJ   rK   rL   rM   rN   rO   rP   gradio.state_holderrQ   gradio.utilsrR   rS   rT   rU   gradio.blocksrV   r  r  r  init	resourcesr  joinpathas_posixSTATIC_TEMPLATE_LIBr  r  r  rE  r!  r"  rs   
gettempdirr  rg   r   rX   envfiltersr  LimitsTimeoutr   r!  r   r  r  r  r  rE  r   rw   ru   <module>rB     s  U U # " " " " "            				       				  



       3 3 3 3 3 3 3 3       % % % % % %                                                     7 6 6 6 6 6 . . . . . . = = = = = = = = / / / / / / 0 0 0 0 0 0 - - - - - - . . . . . . ; ; ; ; ; ; / / / / / / F F F F F F 0 0 0 0 0 0  B B B B B B B B B B B B 5 5 5 5 5 5 " " " " " "                            6 5 5 5 5 5 5 5 ' ' ' ' ' '            & % % % % %                            D C C C C C                  , + + + + +             $######    	   dh''00==FFHH   $h''X)**XZZ	  h''X)**XZZ	  


    :>>"344 D				(*9 9 
? ? ? ? ?\ ? ? ?&   O&9:::	$,	 j !		5<"$   EM$
 
 
 *)++ { { { { {' { { {F<' ' 'T   &
 
 
 
 

 ! (,\ GK#FJ &*&*#&* #' %)"1\ \ \ \ \ \~  rw   