
    U[i                      U 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ZddlmZmZmZ ddlmZ ddlmZ ddlmZ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/m0Z0m1Z1m2Z2m3Z3m4Z4 dd
l5m6Z6 ddl7m8Z8 ddl9m:Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZH ddlImJZJ ddlKZKddlKmLZLmMZMmNZNm:Z: ddlOmPZP ddlQmRZR ddlSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[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llmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZy ddlzm{Z{ ddl|m}Z}m~Z~mZmZmZmZmZ dd lmZ dd!lmZ dd"lmZmZmZmZ erdd#lmZ ddlZddlZddlZddlZ ej(                           e"eXej*                  j-                  d$      j/                  d%      j1                               Z e"eXej*                  j-                  d$      j/                  d&      j1                               Z e"eXej*                  j-                  d$      j/                  d'      j1                               Z e       Zh d(Zej<                  j?                  d)      xs!  e e ejB                               d$z        Z eNjF                          eNjH                          eNjJ                          eNjL                          eNjN                          eNjP                          eNjR                          eNjT                         fD  ci c]  } | jV                  | jV                  |  c} Zd*ed+<    G d, d-e1      Zd. Z e8e/      Zeejb                  jd                  d0<    e$jf                   e$jh                  d1d23       e$jj                  d4      5      Z eo       Z G d6 d7e+      Zd?d@d8ZdAd9ZdBd:Z e=       	 	 	 	 dCdddddddd;ddddddddddddddd<	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDd=       Zg d>Zyc c} w )EzImplements 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Sequence)Path)Empty)TYPE_CHECKINGAnyLiteralUnioncast)	APIRouterBackgroundTasksBodyDependsFastAPIHTTPExceptionstatus)FileResponseHTMLResponseJSONResponsePlainTextResponseResponseStreamingResponse)OAuth2PasswordRequestForm)Jinja2Templates)utils)document)ServerMessage)TemplateNotFound)parse_options_header)BackgroundTask)
UploadFile)RedirectResponse)ranged_responseroute_utilsthemesr   )BrotliMiddleware)Context)
CancelBodyComponentServerBlobBodyComponentServerJSONBodyDataWithFilesDeveloperPathJsonData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NodeProxyCacheRequestcompare_passwords_securelycreate_lifespan_handlermove_uploaded_files_to_cache)process_video_with_ffmpeg)CloseStreamMessageEstimationMessageEventMessageHeartbeatMessageProcessCompletedMessageProcessGeneratingMessageUnexpectedErrorMessage)StateHolder)
ThemeClass)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_DIRzdict[str, Theme]BUILT_IN_THEMESc                  N    e Zd ZdZedd       Zedd       ZddZedd       Zy)	ORJSONResponserf   c                X    t        | t              r| j                         S t        |       S N)
isinstancer/   
model_dumpstrcontents    [/var/www/html/chatbot/Makanify-Chatbot-3/venv/lib/python3.12/site-packages/gradio/routes.pydefaultzORJSONResponse.default   s%    gx(%%''7|    c                    t        j                  | t         j                  t         j                  z  t        j
                        S )Noptionrs   )orjsondumpsOPT_SERIALIZE_NUMPYOPT_PASSTHROUGH_DATETIMErj   rs   rp   s    rr   _renderzORJSONResponse._render   s3    ||--0O0OO"**
 	
rt   c                ,    t         j                  |      S rl   )rj   r|   )selfrq   s     rr   renderzORJSONResponse.render   s    %%g..rt   c                J    t         j                  |       j                  d      S )Nutf-8)rj   r|   decoderp   s    rr   _render_strzORJSONResponse._render_str   s    %%g.55g>>rt   N)rq   r
   returnro   )rq   r
   r   bytes)	__name__
__module____qualname__
media_typestaticmethodrs   r|   r   r    rt   rr   rj   rj      sF    #J 
 
 
/ ? ?rt   rj   c                    t        j                  t        j                  |       j	                  dd      j	                  dd      j	                  dd      j	                  dd            S )	N<z\u003c>z\u003e&z\u0026'z\u0027)
markupsafeMarkuprj   r   replace)values    rr   toorjsonr      sS    ""5)	i	 	i	 	i	 	i	  rt   )	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	e      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 )Appz
    FastAPI App Wrapper
    Nc                   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 | _        |j;                  dd        |j;                  dd        i | _        t?        |   di | y )N   F    r   docs_url	redoc_urlr   )!tokensauthsecretstoken_urlsafeanalytics_keymonitoring_enabledblocksrR   state_holder	iteratorssetiterators_to_resetr   safe_get_locklocksafe_get_stop_event
stop_event	cookie_idqueue_tokenstartup_events_triggeredrW   uploaded_file_dirchange_countchange_typereload_error_message_asyncio_tasksauth_dependencyapi_infoall_app_info
setdefaultcustom_component_hashessuper__init__)r~   r   kwargs	__class__s      rr   r   zApp.__init__   s   
 	$2226"',0'M35,/E'')	335 ..r2"004(-%!2!4!">B04!24.  	*d++t,79$"6"rt   c                x  K   | j                   j                  }|r|j                  |d      }| j                   j                  r|d| j                   j                   z  }| d| d| | }| d| }|r|d| z  }|r||z  }i }	||	d<   t	        |      |	d<   t        j                  d      rd|	d	<   | j                  j                  d
      x}
|
|	d
<   t        j                  j                  | j                  ||	      }t        j                  j                  |       d {   \  }}}t        |||      S 7 w)N ?z://:zx-gradio-serverzx-gradio-portGRADIO_LOCAL_DEV_MODE1zx-gradio-local-dev-modezaccept-languagestatus_codeheaders)urlpathr   queryro   osgetenvr   getr   proxy_cacheProxyReqmethodr   )requestserver_name	node_portpython_portschememounted_path	full_pathr   
server_urlr   accept_language	proxy_reqr   response_headers	aiter_raws                  rr   proxy_to_nodezApp.proxy_to_node   sT     KK$$	!)),;I;;1W[[../00IK=)YK@xs;-0
Ak]++J,&J%/!"#&{#3 99,-14G-.&223DEEOR)8G%&OO,,W^^S'J	47OO4G4G	4R.R+ ) $
 	
 /Ss   DD:!D8"D:c                h   |j                   }|0t        |      s|D ci c]  }|d   |d    c}| _         n|| _         nd | _         || _        t        j                         | _        |j                  | _        i | _        |j                  xs d| _        | j                  j                  |       y c c}w )Nr      r   )r   callabler   r   getcwdcwdfavicon_pathr   	root_pathr   
set_blocks)r~   r   r   accounts       rr   configure_appzApp.configure_appJ  s    {{D>CGHWQZ3H	 	DI99;"//))/R$$V, Is   B/c                H    | j                   t        d      | j                   S )Nz+No Blocks has been configured for this app.)r   
ValueError)r~   s    rr   
get_blockszApp.get_blocksZ  s"    ;;JKK{{rt   c                r   t        j                  |      | j                  sJ t        fd| j                  j                  D              }|st        d      j                  j                  d      }i }t        j                  |rdt        j                   |d<   t        j                  d|      }|S )Nc              3  v   K   | ]0  }j                   t        j                  |      j                   k(   2 y wrl   )hosthttpxURL).0rootr   s     rr   	<genexpr>z*App.build_proxy_request.<locals>.<genexpr>d  s-      
15CHH		$,,,
s   69zThis URL cannot be proxied.z	.hf.spacezBearer AuthorizationGETr   )r   r   r   any
proxy_urlsPermissionErrorr   endswithr)   tokenclientbuild_request)r~   url_pathis_safe_url	is_hf_urlr   rp_reqr   s         @rr   build_proxy_requestzApp.build_proxy_request_  s    ii!{{{  
9=9O9O
 
 !"?@@HH%%k2	==$)0'@GO$%%eS'%Brt   c                T    | j                   D ]  }|j                           g | _         y rl   )r   cancel)r~   tasks     rr   _cancel_asyncio_taskszApp._cancel_asyncio_tasksp  s(    '' 	DKKM	 rt   c                    t         dz   }|1t        j                  j                  dd      j	                         dk(  }|rW	 dd l}	 |j                  j                          _	        d _
        d d|v r|d   t        j                  d fd	       }||d<    j                          _        |S # t        $ r}t        d      |d }~ww xY w# t        $ r}d
 _
        d|  _        Y d }~Sd }~ww xY w)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lifespanc               j  K   t        j                         4 d {   }j                  r2|j                  j                  j	                  |              d {    |j                   |              d {    d  d d d       d {    y 7 y7 =7 7 # 1 d {  7  sw Y   y xY wwrl   )
contextlibAsyncExitStackmcp_server_objenter_async_contextr  )appstackr   user_lifespans     rr   	_lifespanz'App.setup_mcp_server.<locals>._lifespan  s     )88:  e!00"'";"; & 5 5 > >s C#   )4"'";";M#<N"OOO   P   sh   B3BB3:BB B;B<	BB3BB3BBB3B0$B'%B0,B3FzError launching MCP server: )r  r   )r=   r   environr   lower
gradio.mcpImportErrormcpGradioMCPServerr  
mcp_serverr  asynccontextmanager	Exception	mcp_errorget_config_fileconfig)r   
app_kwargsr  mcp_subpathrY   er  r  s   `      @rr   setup_mcp_serverzApp.setup_mcp_serveru  s    !6)(;WEKKMQWWJ!
F(.

(B(B6(J%$(! $+$.z$:M// 0 *3
:& ""$ 	 =  ! Z.  F$)!%A!#E  Fs1   B/ AC /	C	8CC		C0C++C0c                   6789:;<=>?@ABCDEFGHIJKLM |xs i }|j                  dt               t        j                   ||      } j                  xs d}t        |j                  dd       g| |d<   t        dd|i|ddi7 j                  r' j                  j                  7| j                         t        t              }7j                          7j                  t        |       7j                  t        d	|g
       |r7j!                  d      	 	 d fd       }	|j                  d      |j                  d      d7fd              ?|j                  d      |j                  d      t#        ?      fd7 fd              }
|j                  d      |j                  d      d7fd              }|j                  d      |j                  d      d7fd              }|j                  dt#        |
      g      	 	 d7fd       }7j%                  d      7j%                  d      t#               f	 	 	 d7fd              }7j&                  "7j&                  j(                  rt+        7       n+7j                  d      t#        ?      df	 	 	 	 	 d7fd        }7j                  d!      dd"       }7?Efd#} j,                  D ]  }|d$   }|d%k7  s ||        	 d	 	 	 	 	 d7fd&D7j/                  d't0        (      7j                  d't0        (      t#        ?      d%d%f	 	 	 	 	 	 	 d67Dfd)              E7j                  d*      d7fd+       }|j                  d,t#        |
      g      |j                  d-t#        |
      g      d7fd.              6|j                  d/t#        |
      g      d67fd0       }7j                  d1t#        |
      g      7j                  d2t#        |
      g      dd7 ?Dfd3              }7j                  d4      dd5       J|j                  d6      	 	 	 	 	 	 	 	 	 	 d7fd7       }7j                  d8      dd9       }7j                  d:      7Jfd;       }|j/                  d<t#        |
      g      |j                  d<t#        |
      g      d7fd=              }|j/                  d>t#        |
      g      |j                  d>t#        |
      g      d7fd?              =|j%                  d@      d7fdA       }|j%                  dB      d7fdC       }|j                  dD      d7fdE       }|j                  dF      	 	 	 	 	 	 	 	 	 	 d7fdG       }|j                  dH      d7fdI       }|j                  dJt#        |
      g      d=fdK       }|j%                  dL      |j%                  dM      ddN              }|j                  dO      t#        ?      f	 	 	 	 	 	 	 d7fdP       }|j%                  dQt#        |
      g      |j%                  dRt#        |
      g      |j%                  dSt#        |
      g      |j%                  dTt#        |
      g      t#        ?      f	 	 	 	 	 	 	 d7fdU                            }|j%                  dVt#        |
      g      |j%                  dWt#        |
      g      t#        ?      f	 	 	 	 	 	 	 d7GfdX              }|j%                  dYt#        |
      g      t#        ?      f	 	 	 	 	 dGfdZ       } 	 	 	 	 	 	 d7fd[G|j%                  d\      d7fd]       }!|j                  d^t#        |
      g      	 	 	 	 dFfd_       }"|j                  d`t#        |
      g      	 	 	 	 dFfda       }#	 	 	 	 	 	 d7fdbF	 	 	 	 ddc@|j%                  ddt#        |
      g      |j%                  det#        |
      g      	 	 d7@fdf              }$|j                  dgt#        |
      gt2        h      7fdi       }%|j                  dj      ddk       }&|j%                  dlt#        |
      g      	 d	 	 	 	 	 d7 fdm       }'|j                  dn      7fdo       }(|j                  dpt4        (      7j                  dpt4        (      7fdq              })7j                  drt4        (      7fds       }*7j                  dt      7j                  du      dd7fdv              }+7j                  dw      7 fdx       },7j                  dyt#        |
      g      d7 fdz       }-7j                  d{      7fd|       }7j                  d}      d7 fd~       }.|j%                  dt#        |
      g      	 	 d:fd       }/t7        t8              dz  MMj;                  dd       dd%i8i AdddCt=        j>                  d      ;t=        j>                  dt<        j@                        >t=        j>                  dt<        j@                        <t=        j>                  dt<        j@                  t<        jB                  z        Ht=        j>                  dt<        j@                  t<        jB                  z        LdĈ;<>fd9dňLfdKdƈHfdI jD                  rd$dl#m$}0  |0       B|j%                  d      |j%                  d      dǈ 89ABCIKMf	d              }1|j%                  d      |j%                  d      tK        dd      fdȈ 8AMfd              }2|j                  d      |j                  d       fd              }3|j%                  d      |j%                  d      dɈ fd              }4|j%                  d      |j%                  d       9BKfd              }5d :7jM                  |       7S )Ndefault_response_class)NNr  r   debugT)prefix)strict_cors   )qualityexcluded_handlershttpc           	       K   j                   }|4| j                  j                  j                  j                   xs dd      n| j                  j                  t	        dd       Չj
                  t        fdt        D              st        j                  @| j                  j                  xs t        t        j                  dd            t        _	        	 t        j                  | j                  xs dj
                  t        j                  | j                  j                   |xs d       d {   S  ||        d {   }|S 7 # t"        $ r}t%        |       Y d }~-d }~ww xY w7 )w)Nr   node_processc              3  F   K   | ]  }j                  d |         yw)/N)
startswith)r   r   r   s     rr   r   zIApp.create_app.<locals>.conditional_routing_middleware.<locals>.<genexpr>  s      Vs!C5	 :Vs   !GRADIO_SERVER_PORT78600.0.0.0)custom_mount_pathr   r   r   getattrr   r   INTERNAL_ROUTESr   app_portportintr   r   r   node_server_namer   r!  print)r   	call_nextr:  r'  responser   r   s        @rr   conditional_routing_middlewarez6App.create_app.<locals>.conditional_routing_middleware  sA     %+$<$<! )4 KK$$,,V-E-E-KRP ))  FND9E((4VoVV||+'.{{'7'7 (3II&:FC<
!%(%6%6#"33@y",,LL#KK..-3&    "+7!33  % !a!3sO   CE6AE :E;E >E6
E4E6E 	E1E,'E6,E11E6z/userz/user/c                   j                   j                  |       S | j                  j                  dj                         xs( | j                  j                  dj                         }j                  j                  |      S )Naccess-token-access-token-unsecure-)r   cookiesr   r   r   r   r   r  s     rr   get_current_userz(App.create_app.<locals>.get_current_user  s     "".**733OO''/ O$$'=cmm_%MN  ::>>%((rt   z/login_checkz/login_check/c                    j                   j                  | y t        t        j                  dj
                  d      )NNot authenticatederrorauth_messager   detail)r   r   r   r   HTTP_401_UNAUTHORIZEDrO  )userr  r   s    rr   login_checkz#App.create_app.<locals>.login_check  sI      S%8%8%@TEU"880$*$7$7 rt   z/tokenz/token/c                    | j                   j                  dj                         }|j                  j                  |      dS )NrF  )r   rS  )rH  r   r   r   rI  s     rr   	get_tokenz!App.create_app.<locals>.get_token  s<     OO''-(GHE"CJJNN5,ABBrt   z/app_idz/app_id/c                <    dj                         j                  iS )Napp_id)r   rX  )r   r  s    rr   rX  zApp.create_app.<locals>.app_id  s     cnn.5566rt   z/dev/reload)dependenciesc                >   K   dfd}t         ||       d      S w)Nc                 K   d}d}t        j                         }j                  }	 | j                          d {   ry j                  |k7  rSj                  }j                  dk(  r t        j                  j                         nd}dj                   d| d t        j                  |       d {    t        j                         |z
  |kD  rd t        j                          }7 7 :w)	N   皙?rN  z{}event: 
data: 

zevent: heartbeat
data: {}

)
timeperf_counterr   is_disconnectedr   jsonry   r   asynciosleep)r   heartbeat_rate
check_ratelast_heartbeatcurrent_countmsgr  s         rr   reload_checkerz>App.create_app.<locals>.notify_changes.<locals>.reload_checker  s     !#!
!%!2!2!4 # 0 0$44666''=8(+(8(8  #'9 !JJ#*B*B)CE!% 
 #*#//):(3%tNN!--
333((*^;nLBB)-! 6 4s"   9C9C5A?C9<C7=9C97C9text/event-streamr   r   fastapi.Request)r   )r   rl  r  s     rr   notify_changesz&App.create_app.<locals>.notify_changes  s&     50 %w'. s   /loginz/login/c                2  K   |j                   j                         |j                  }}j                  =t	        j
                  | dj                        }t        |t        j                        S t        j                        s'|j                  v rt        |j                  |         sat        j                        rt        j                  j                        rj                  ||       d {   rnj                  ||      rxt        j                  d      }|j                   |<   t#        ddi      }|j%                  dj&                   |dd	d
       |j%                  dj&                   |d       |S t)        dd      7 w)Nrr  r   
route_pathr   r   r   r   successTrp   rF  none)keyr   httponlysamesitesecurerG  )ry  r   rz    zIncorrect credentials.rP  )usernamestrippasswordr   r&   get_root_urlr   r$   r   HTTP_302_FOUNDr   rG   inspectiscoroutinefunctionr   r   r   r   
set_cookier   r   )r   	form_datar~  r  r   r   rC  r  s          rr   loginzApp.create_app.<locals>.login(  sq    
 "+!3!3!9!9!;Y=O=OhHxx"//#'!mm
 (Df>S>STTSXX&(.x(9KL" 22388< ((8X666(H5  --b1$,

5!'D0AB##'7!# $  ##0@! $ 
  #<TUU- 7s   C5F8F9BF/logoutc                h   t        j                  | dj                        }t        |t        j
                        }|j                  dj                   d       |j                  dj                   d       |rJt        j                  j                               D ]"  }j                  |   |k(  sj                  |= $ |S | j                  j                  dj                         j                  v r3j                  | j                  j                  dj                         = |S )Nr  rt  rv  rF  r5  )ry  r   rG  )r&   r  r   r$   r   r  delete_cookier   listr   keysrH  r   )r   rS  all_sessionr   rC  r   r  s         rr   logoutzApp.create_app.<locals>.logout_  s    #//#(!mm
 ,&BWBWX&&]3==/+JQT&U&&0@s '  !%cjjoo&7!8 2::e,4 #

5 12   __((=)HISZZW

7??#6#6s}}o7V#WXrt   z/svelte/{path:path}c           	         t        t              dz  }t        t        t	        t        |            t        |                   S )Nsvelte)r   BUILD_PATH_LIBr   routes_safe_joinr.   ro   r4   )r   svelte_paths     rr   _zApp.create_app.<locals>._}  s;    ~.9K !#k"235Ed5K rt   c                     j                  d  t              j                  d  dt              t              df	 	 	 	 	 d fd              }y )Nr5  response_classr   c                     | ||      S rl   r   )r   rS  	deep_linkmainpages      rr   
page_routez7App.create_app.<locals>.attach_page.<locals>.page_route  s     GT4;;rt   )r   rp  rS  ro   r  ro   )r   r   r   )r  r  r  rJ  r  s   ` rr   attach_pagez#App.create_app.<locals>.attach_page  sm    WWqZW=WWqa[W> $$45!#<(<< < ? ><rt   r   r   c                `   |d   }	 t        j                        dz  | z  dz  }|j                         r&t        j                  |j                               }d}nd}|r|D cg c]  }|d   |d   |   d   v r| }}||fS # t        t        t        j                  f$ r d}g }Y Iw xY wc c}w )N
components
deep_links
state.jsonvalidinvalididr  )	r   r   existsrx   loads
read_bytesFileNotFoundErrorOSErrorJSONDecodeError)r  r$  r  r  r   deep_link_state	componentr  s          rr   load_deep_linkz&App.create_app.<locals>.load_deep_link  s      -J ../"#  ##  ;;=!'doo.?!@J&-O&/O  &0! &.*>|*LL 
 
 .. &w0F0FG  "+
 s   AB $B+"B('B(r5  r  c           
        t        j                  dd       j                         }t        j                  | d| j
                  xs |j                        }j                  j                  |t        j                  |j                        }d}|d   D cg c]  }|d   |d   |   d   v r| }	}|r |||      \  }	}||d	<   ||d
<   |	|d<   |j                  dg       D 
cg c]  }
|
d   |d   |   d   v r|
 c}
|d<   |d   |   d   |d<   ||d<   t        j                  ||      }nY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(        j+                  | |||d      }|S c c}w c c}
w # t,        $ r)}|j&                  rt/        d      |t/        d      |d }~ww xY w)Nzapplication/javascriptz.jsr5  rt  rx  r  r  r  r~  r  rY  layoutcurrent_pagerL  rM  rP  Tr   )	auth_requiredrO  space_idr   r  pagesr  rY  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   r:  r   r   r   safe_deepcopyr$  r   update_root_in_configr   r   rR  rO  r  sharerZ   TemplateResponser    r   )r   rS  r  r  r   r   r$  r  r  r  
dependencytemplater  resperrr   r  r  s                  rr   r  zApp.create_app.<locals>.main  s    7?^^%F++tf:--C6+C+CD
  S%8%8%@TEU,,V]];"( &,L%9! &.*>|*LL 
 
 2@!3/J
 &*z",;()'1|$ '-jj&D*"!$'6&>$+?+OO *~&
 $*&>$#7#Ax )-~& %::64H$$# & < <!4(.(;(;  &*$*$7$7 & (B0 T"$$&$&
-3\\)?T  #+7"3 11#!"(+: 2  u*Z $ 
<<$R 
 %M 
s$   G*G4G 	G>$G99G>z/gradio_api/deep_linkc                
   | j                   v rj                   |    j                  D cg c]  }t        j                  |       }}t	        j
                  |t        j                  t        j                  z  t              }t        j                  |      }t        j                        dz  |z  }|j                  dd       t        |dz  d      5 }|j                  |       d d d        |S yc c}w # 1 sw Y   |S xY w)Nrv   r  T)parentsexist_okr  wbr   )r   r  r   r  rx   ry   rz   r{   ro   r&   create_url_safe_hashr   r   mkdiropenwrite)session_hashcr  components_jsonr  r   fr  s          rr   r  z!App.create_app.<locals>.deep_link
  s    s/// !--l;FF ''*
  #),,!558W8WW#
 (<<_M	 !6!67,FR	t<)l2D9 -QGGO,-  !-  s   C3C88Dz/info/z/infoc                   | j                   j                  dd      }|r=j                  s%j                         j	                  d      _        j                  S j
                  sjt        j                  j                         j	                               }t        t        t        t        f   |      }t        j                  |      }|_        j
                  S )Nall_endpointsFT)r  )query_paramsr   r   r   get_api_infor   r   r  r   dictro   r
   r&   'update_example_values_to_use_public_url)r   r  r   r  s      rr   r   z App.create_app.<locals>.api_info  s     $0044_eLM'''*~~'7'D'DSW'D'XC$'''<< ..s~~/?/L/L/NOS#X9&NNxX'<<rt   z/openapi.jsonc                    |       }dt        j                         dd      t        j                         dd      t        di di id}|j                  d	i       j	                         D ]  \  }}|j                  d
d      dk(  rd|j                  dd|       |j                  dd      |j                  d      j                  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   }|j                  dg       D ]  }|d   }|j                  d i       }	d!|	v rt        |	      }	|	j                  d!d"       d|	v rd |	vrt        |	      }	d|	d <   |	||<   d#|v s]d$|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        |j                  d(g             D ]a  \  }}|d)kD  rd*| nd+}|j                  d i       }d!|v rt        |      }|j                  d!d"       d|v rd |vrt        |      }d|d <   ||
|<   c ||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api_visibilitypublicprivatepostz	Endpoint r5  r  Trf   schemaobject)type
properties)requiredrq   200zSuccessful response)r  rq   )summaryr  operationIdrequestBody	responsesr  rq   r  
parametersparameter_namer  additional_descriptionNexample_inputexamplesexample1r   r  returnsr   output_outputr  z/run)
r;  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                  rr   openapi_schemaz&App.create_app.<locals>.openapi_schema.  s    G$D"$S^^%5wM#*3>>+;]B#O&
 ("o	F 159JB0O0U0U0W OD,} $$%5x@IM#0#4#4)Y}o+F$ (5'8'8'K'4':':3'?'G'GS'Q(, 2$,xr.R5"(( "/D$6(08SU2V9&,"$	&	8 &/v%6}%Ei%P&&&(&*" +..|R@ TE!&'7!8J!&62!6J/:=%)*%5
"'?F#z1fJ6N%)*%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;1T8 '0&7&DU&KI&V&''('*# ((9(9)R(HI =FAs01A}8H"wwvr2H/8;#'> %=tD#x/F(4J#'>+3(4<'1= ;Dw$}o 67_ODb Mrt   z/config//configc                   t        j                  j                         j                        }t	        j
                  | dj                  xs j                        } |       |d<   |r 	||d      \  }}||d<   ||d<   t        d      r&j                  rj                  j                  |d	<   nd |d	<   t	        j                  ||      }t        |
      S )Nr  rt  r~  r   )r  r  r  i18n_instancei18n_translationsrp   )r   r  r   r$  r&   r  r   r:  hasattrr  translations_dictr  rj   )
r   r  r$  r   r  r  r  r   rJ  r  s
         rr   
get_configz"App.create_app.<locals>.get_config  s     (()9)@)@AF++$--C6+C+CD
 "2'!:F:.<YUW.X+
O'1|$,;()v/F4H4H.4.B.B.T.T*+.2*+ 66vtDF!&11rt   z/static/{path:path}c                J    t        t        t        |             }t        |      S rl   )r  STATIC_PATH_LIBr4   r   )r   static_files     rr   static_resourcez'App.create_app.<locals>.static_resource  s    *?<LT<RSK,,rt   z7/custom_component/{id}/{environment}/{type}/{file_name}c           	         |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|             }	t        t        t        t        |      j                               t        |	            }
  d| d| }|j"                  vrWt%        j&                  t        |
      j)                  d	
      j+                               j-                         j"                  |<   j"                  j/                  |      }ddi}|r||d<   |r+|j0                  j/                  d      |k(  rt3        d|      S t5        |
|      S # t        $ r t        dd      d w xY w)N)r   server  zEnvironment not supported.rP  c              3  J   K   | ]  }|j                         k(  s|  y wrl   )get_component_class_id)r   itemr  s     rr   r   z@App.create_app.<locals>.custom_component_path.<locals>.<genexpr>  s"     T$0K0K0MQS0STs   ##zComponent not found.r5  -r   )encodingzCache-Controlzmax-age=0, must-revalidateETagzif-none-matchi0  r   r   )r   r   get_all_componentsnextr   sysmodules__file__	safe_joinTEMPLATE_DIRr4   r8   r  r.   ro   r   parentr   hashlibsha256	read_textencode	hexdigestr   r   r   r   )r  environmentr  	file_namereqr  locationmodule_namemodule_pathrequested_pathr   ry  r  r   r  s   `             rr   custom_component_pathz-App.create_app.<locals>.custom_component_path  s    "66# #,H  113JT*TH #<RSS"--K++k2;;K"#<RSS!&))$vQyk%:;" $c${"3":":;< 0D D$q,C#5553:>>J(('(:AAC4)+ ++C0 1155c:G&(DEG")3;;???;wF(S'JJg66; $ # #,Bs   .F< <Gz/assets/{path:path}c                J    t        t        t        |             }t        |      S rl   )r  r  r4   r   )r   
build_files     rr   build_resourcez&App.create_app.<locals>.build_resource  s    ).:J4:PQJ
++rt   z/favicon.icoc                 ~   K   j                         } | j                   d      S t        | j                        S w)Nzimg/logo.svg)r   r   r   )r   r  r  s    rr   faviconzApp.create_app.<locals>.favicon  s;     ^^%F""*&~66#F$7$788s   :=z/proxy={url_path:path}c                  K   	 j                  |       }t        j                  |d       d {   }t        j                  |       \  }}|t        vr:|j                  j                  ddi       |j                  j                  ddi       t        |j                         |j                  |j                  t        |j                        	      S # t        $ r}t        dt        |            |d }~ww xY w7 ʭw)
Nr}  rP  T)streamContent-Disposition
attachmentContent-Typeapplication/octet-stream)r   r   
background)r  r   r   ro   r   sendr  
guess_typeXSS_SAFE_MIMETYPESr   updater   r   r   r"   aclose)r  r  r  rp_resp	mime_typer  r  s         rr   reverse_proxyz%App.create_app.<locals>.reverse_proxy  s     O00: #KKtK<<G$//9LIq 22&&(=|'LM&&8R'ST$!!##//)'..9	  # O#CHE3NO<s2   C=C C=C;B"C=	C8C33C88C=z/file={path_or_url:path}c                  K   j                         }t        j                  |       rt        | t        j
                        S t        j                  |       rt        dd|  d      t        j                  |       }	 |j                         s|j                         st        dd|  d      	 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	|xs d	}
d
}nd	}
d}|j2                  j5                  dd      j7                         }|j9                  d      rd|v r|dd  }|j;                  d      \  }}|j=                         r|j=                         rwt?        |      }t?        |      }tA        |j2                        }||d<   |
|d<   tC        jD                  |tC        jF                  ||      |tI        jJ                  |            }|S tM        |ddi||
|jN                        S # t        $ r}t        dd|  d      |d }~ww xY ww)Nrv    zFile not allowed: .r   )_StaticFiles)blocked_pathsallowed_pathscreated_pathsallowedr7  inliner5  Ranger   zbytes=r     r4  r6  )stat_resultzAccept-Rangesr   )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_classesrD  is_allowed_filerE  rF  	all_pathsr   get_cache_folderr  r:  r;  r   r   r  r6  split	isnumericr?  r  r%   RangedFileResponse	OpenRanger   statr   r  )path_or_urlr   r   abs_pathr'  rD  rH  reasonr?  r  r   rM  	range_valstartendr   rC  r  s                    rr   filezApp.create_app.<locals>.file	  su     ^^%F,,[9'#1F1F  //<#C+=k]!)LMM}}[1HU??$HOO,='/A+a-PQQ ->
 9#33$22$22\5K5KK"44e6L6L6NO	OGV #C+=k]!)LMM$//9LIq..&I2E&D*D
+3(7
+7(++GR8>>@I##H-#2B%abM	&__S1
s??$JEc(C"7??3G5MG12.8GN+.AA '11%=$&GGH$5	 H $O('2)A%! Q  U#C+=k]!)LMSTTUs+   A;J?0I  /F1J 	I?)I::I??Jz/stream/{event_id}c                   K   j                         j                  j                  |    }t        di |j	                         d|i}||_        |j                  j                          ddiS w)Nr   rk  rw  r   )r   _queueevent_ids_to_eventsr1   rn   datasignalr   )event_idbodyr   eventr  s       rr   r  zApp.create_app.<locals>._K  s_     NN$++??IE&L):LGLDEJLL9%%s   A*A-z/stream/{event_id}/closec                   K   j                         j                  j                  |    }t        j                  |_        d|_        |j                  j                          ddiS w)NTrk  rw  )	r   re  rf  mathinfrun_timeclosedrh  r   )ri  rk  r  s     rr   r  zApp.create_app.<locals>._S  sQ     NN$++??IE!XXENELLL9%%s   A"A%z9/stream/{session_hash}/{run}/{component_id}/playlist.m3u8c                v  K   j                         j                  |    j                  |i       j                  |d       }|st        d      S d|j                   d}|j
                  D ]-  }|d|d   ddz  }||d	    |d
    dz  }|d
   dk(  s)|dz  }/ |j                  r|dz  }t        |d      S w)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rq   r   )r   pending_streamsr   r   max_durationsegmentsended)r  runcomponent_idr3  playlistsegmentr  s         rr   r  zApp.create_app.<locals>._[  s        /S"\4(	  C00TU[UhUhTi  jW  XH!?? 9hwz':3&?sCCwt}ogk.B-C2FF ;'50 88H9 ||.. -L s   BB9%B9z>/stream/{session_hash}/{run}/{component_id}/{segment_id}.{ext}c                n  K   |dvrt        dd      S j                         j                  |    j                  |i       j                  |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 w)N)aactsr}  zUnsupported file extension)r   rq   r  zStream not foundc              3  4   K   | ]  }|d    k(  s|  yw)r  Nr   )r   s
segment_ids     rr   r   z,App.create_app.<locals>._.<locals>.<genexpr>  s     P!!D'Z:OAPs   zSegment not foundr  rg  z	audio/aacrv  z
video/MP2T)r   r   rw  r   r  ry  )r  r{  r|  r  extr3  r~  r  s      `   rr   r  zApp.create_app.<locals>._x  s      -'C9UVV  /S"\4(	  C9KLLPvPRVWGC9LMMe|KPPLQQs   B1B5z9/stream/{session_hash}/{run}/{component_id}/playlist-filec                  K   j                         j                  |    j                  |i       j                  |d       }|st        d      S |j                  sp|j
                  D cg c]  }|d   	 }}j                         j                  |      j                  |d|j                         d {   }|j                  |_        t        |j                        S c c}w 7 /w)Nr  rr  rg  T)	only_filedesired_output_format)r   rw  r   r   combined_filery  get_componentcombine_streamr  r   r   )r  r{  r|  r3  r  stream_datar  r  s          rr   r  zApp.create_app.<locals>._  s        /S"\4(	  C00''28//BQqyBB..*"]<0#^#"&.4.J.J $   (5'9'9$ 4 455 Cs   A&C')C 5A C'5C%60C'z/file/{path:path}c                2   K    | |       d {   S 7 wrl   r   )r   r   rc  s     rr   file_deprecatedz'App.create_app.<locals>.file_deprecated  s     dG,,,,s   z/reset/z/resetc                   K   ddiS w)Nrw  Tr   )rj  s    rr   reset_iteratorz&App.create_app.<locals>.reset_iterator  s      t$$s   z/heartbeat/{session_hash}c                z     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      ?r\  c            
    4  K   t        j                  j                  j                               } 	 	 d t        j                  t        j                              }t        j                  || gt         j
                         d {   \  }}| |v rt        j                         	 z7 !# t         j                  $ r | j                         s| j                          t              }t        j                  t         d j                        }t        g       }j                         j                   j#                         D cg c]#  \  }}t%        d |j&                  D              r|% nc c}}w }	}}|	D ]B  }
j)                  t        j*                  ||j                         j                   |
   |	       D j,                  j.                  v rdj,                  j.                     _        j                         j2                  j4                  j7                  g       D ]X  }j                         j2                  j8                  |   }t:        j<                  |_        |j@                  jC                          Z Y y w xY ww)
NTzdata: ALIVE

)return_whenr  z/heartbeat/rt  )r  rg  r   c              3  2   K   | ]  }|d    dk(  s|  yw)r   unloadNr   )r   ts     rr   r   zFApp.create_app.<locals>.heartbeat.<locals>.iterator.<locals>.<genexpr>  s     "NQqTX=M1"Ns   r  rj  
gr_requestfnr   )"re  create_taskr   waitrf  FIRST_COMPLETEDCancelledErrordoner  rF   r&   r  r=   r   r1   r   fnsr  r   targetsadd_taskcall_process_apir   session_data	is_closedre  pending_event_ids_sessionr   rf  rm  rn  ro  rh  r   )stop_stream_task	wait_taskr  r  r'  r   rj  r  depunload_fn_indicesfn_indexri  rk  r  background_tasksrg  r   r  r~  s                rr   iteratorz3App.create_app.<locals>.heartbeat.<locals>.iterator  s`    #*#6#6s~~7J7J7L#M 5// %,$7$7n8U$V	(/&(89(/(?(?) #a ,t3")"8"8":: 4 # #11 */446,335%gxlS$/$<$<$+*4['O&)mm%	
  3)5B 
 +...*:*>*>*D*D*F- &3""Nckk"NN - -) -
 ): 
H -55 + < <$'%)+.#&>>#3#7#7#A*3 6 
 (3+;+;+H+HHTXC,,99,GQ !^^-44NNRR("	/$ %(NN$4$;$;$O$O (%E .2XXEN!LL,,.	/ U*sI   /JAB. 
B,B. *J,B. .B&J(E=<DJJJJrm  rn  )r   r   r   )r  r   r  r~  r  rg  r  s   ```` @rr   	heartbeatz!App.create_app.<locals>.heartbeat  s8     &(YY/CT%JTPRN8 8t %XZ<OPPrt   z/run/{api_name}z/run/{api_name}/z/api/{api_name}z/api/{api_name}/c                  K   t        di |j                         d|i}t        j                  
j	                         | |      }
j	                         j
                  s'|j                  rt        dt        j                        t        j                  ||||      }t        j                  |t         d|  
j                        }	 t        j                  
||||       d {   }t3        |      S 7 # t        $ ru}t!        j"                  |
j	                         j$                        }	t'        |t(              r|j*                  rt-        j.                          t1        |	d	
      cY d }~S d }~ww xY ww)Nr   r   api_namerj  zcThis API endpoint does not accept direct HTTP POST requests. Please join the queue to use this API.)rQ  r   )r  r~  r   z/api/rt  r    )rq   r   r   )r1   rn   r&   get_fnr   api_openqueuer   r   HTTP_404_NOT_FOUNDcompile_gr_requestr  r=   r   r  BaseExceptionr   error_payload
show_errorrm   r7   print_exception	traceback	print_excr   rj   )r  rj  r   r~  r  r  r   r  rN  rq   r  s             rr   predictzApp.create_app.<locals>.predict  sX     'L):LGLD##~~'(B >>#,,# A & 9 9  %77!	J $00(\xj9--I
*;;)'   "&)) ! --eS^^5E5P5PQ!%/53H3H'')## # 	sI   C	E=C< *C:+C< /E=:C< <	E:A*E5/E:0E=5E::E=z/call/{api_name}z/call/{api_name}/c                   K   t        di |j                         ddi}t        j                  j	                         | |      }|j
                  |_         |||       d {   S 7 w)Nsimple_formatTr  r   )r0   rn   r&   r  r   _idr  )r  rj  r   r~  	full_bodyr  r  queue_join_helpers         rr   simple_predict_postz+App.create_app.<locals>.simple_predict_post0  sc      $Ldoo&7LtLI##~~'(B "$I*9gxHHHHs   A"A,%A*&A,z/queue/joinc                   K   | j                   t        t        j                  d       | ||       d {   S 7 w)NzSession hash not found.rP  )r  r   r   HTTP_400_BAD_REQUEST)rj  r   r~  r  s      rr   
queue_joinz"App.create_app.<locals>.queue_join?  sE        (# & ; ;4  +4(CCCCs   5?=?c                0  K   	j                         }|j                  j                  |j                  j                  	       |j                  j                  rt        t        j                  d      t        di | j                         d|i} |j                  j                  | ||       d {   \  }}}t        j                  t        j                  t        j                  t        j                  d}|s||   }t        ||      d|iS 7 _w)NzQueue is stopped.rP  r   )rj  r   r~  )
queue_fullvalidator_errorrN  rw  ri  r   )r   re  
server_appset_server_appstoppedr   r   HTTP_503_SERVICE_UNAVAILABLEr1   rn   pushHTTP_422_UNPROCESSABLE_ENTITYr  HTTP_200_OK)
rj  r   r~  r   rw  ri  state	error_mapr   r  s
            rr   r  z)App.create_app.<locals>.queue_join_helperL  s     
 ^^%F}}''/,,S1}}$$# & C C.  'L):LGLD-3]]-?-?7X .@ . ($GXu %AA#)#G#G44!--	I '.#HMM))(s   B1D4D5A Dz/cancelc                  K   t        | j                   d| j                   h       d {    j                         }| j                  |j                  j
                  v }| j                  |j                  j                  j                  | j                  i       v }|rL|rJt        i d| j                        }|j                  j
                  | j                     j                  |       | j                  j                  v rej                  4 d {    j                  | j                  = j                  j                  | j                         d d d       d {    ddiS ddiS 7 B7 [7 # 1 d {  7  sw Y   ddiS xY ww)Nr  T)r  rw  ri  rw  )rT   r  r  r   re  pending_messages_per_sessionri  r  r   rO   
put_nowaitr   r   r   add)rj  r   session_openevent_runningmessager  s        rr   cancel_eventz$App.create_app.<locals>.cancel_eventk  sj    4#4#4"5Qt}}o FGHHH^^%F !!V]]%O%OO  ==::>>t?P?PRTUV  1tdmm ::%%*W%}}-88 > >dmm4**..t}}=> > t$$It$$+ I$> > > > > t$$sX   )FE.C(FE1F=E5F!E3"F1F3F5F
;E><F

Fz/call/{api_name}/{event_id}c                <   K   dd} | ||       d {   S 7 w)Nc                   | j                         }t        | t              r%| j                  rdnd}|d   j	                  d      }njt        | t
              r%| j                  rdnd}|d   j	                  d      }n5t        | t              rd}d }n t        | t              rd}| j                  }ny d| dt        j                  |       d	S )
NcompleterN  r  rg  
generatingr  r^  r_  r`  )rn   rm   rO   rw  r   rP   rN   rQ   r  rd  ry   )r  rk  rk  rg  s       rr   process_msgz?App.create_app.<locals>.simple_predict_get.<locals>.process_msg  s    ((*g'>?*1//JwEx=,,V4D)AB,3OOLEx=,,V4D)9:'ED)?@#E"??D x

40@/AFFrt   )r  rM   r   
str | Noner   )r   ri  r  queue_data_helpers      rr   simple_predict_getz*App.create_app.<locals>.simple_predict_get  s$     
G$ +7HkJJJJ   z/queue/datac                <   K   dd} | ||       d {   S 7 w)Nc                z    dt        j                  | j                         t              j	                  d       dS )Ndata: )rs   r   r`  )rx   ry   rn   ro   r   )r  s    rr   r  z7App.create_app.<locals>.queue_data.<locals>.process_msg  s3    W-?-?-A3 O V VW^ _``deert   )r  rM   r   ro   r   )r   r  r  r  s      rr   
queue_dataz"App.create_app.<locals>.queue_data  s$     
f +7L+NNNNr  c                h   K   j                         dfd}t         ||       d      S w)Nc                 K   	 t        j                         }	 | j                          d {   r%j                  j	                  
       d {    y 
j                  j
                  vrt        t        j                        d}t        j                         dk(  rdnd}d }	 j                  j
                  
   }|j                         }j                  j                   rt#        dd	      }|r 	|      }|| t%        |t&              r|j(                  r|j(                  j                  j*                  
   v r2j                  j*                  
   j-                  |j(                         |j.                  t0        j2                  k(  sB|j.                  t0        j4                  k(  r?t7        j                  j*                  
         d
k(  rt9               } 	|      }|| y 7 7 # t        $ rZ t        j                  |       d {  7   t        j                         |z
  |kD  rt               }t        j                         }Y w xY w# t:        $ r}t#        t=        |      t%        |t                    } 	|      }t%        |t        j>                        r<j                  j
                  
= j                  j	                  
       d {  7   || |d }~ww xY ww)Nr  rr  r\  Windowsr]  gMbP?zServer stopped unexpectedly.F)r  rw  r   )r  session_not_found) ra  rb  rc  re  clean_eventsr  r   r   r  platformsystem
get_nowait
EmptyQueuere  rf  rN   r  rQ   rm   rO   ri  r  removerk  r   server_stoppedprocess_completedlenrK   r  ro   r  )r   ri  rg  rh  r  messagesrC  r'  r   r  r  s           rr   
sse_streamz=App.create_app.<locals>.queue_data_helper.<locals>.sse_stream  s    W%)%6%6%8N!(!8!8!:::"(--"<"<,"<"WWW" )#)==#M#MN #0,2,E,E#  *,-5__->)-KTQV
"&E'-}}'Q'Q ,(H '/&9&9&;G "==00&<(F(-'G #'27';H'3&. *74K L$+$4$4 %,$4$4(.(O(O,8)*%& %+MM$K$K(4%&&,fW-=-=&>#*;;-2N2N#N$+KK=3R3R$R(+,2MM,S,S0<-.)*
 ,-)- /A.BG/:7/CH'/';.6$*S :W&  * E")--
";;;#002^CnT*:*< 261B1B1DEj % 4 #A*4Q*FG  +73H!!W%;%;<"MMFF|T$mm88l8SSS+&Gs   K<(I  G4#I  G7I  K<AI  ))G: DI  1K<2I  7I  :!IH=II  II   	K9)A<K4%K(&K44K99K<rm  rn  ro  )r   r   )r   r  r  r  r   r  s    `` @rr   r  z)App.create_app.<locals>.queue_data_helper  s6     
 ^^%FXt %7#. s   ,2c                  K   | j                   j                  d      }t        |t              r^|j	                  d      rLg }i }| j                         4 d {   }|j                         D ]  \  }}t        |t              rt        |      dkD  ryt        |d   t              rft        |      D ]W  \  }}t        |t              r8|j                  }	|j                          d {   }
|j                  |	|
f       N||| d| <   Y t        |t              r8|j                  }	|j                          d {   }
|j                  |	|
f       |||<    d d d       d {    t        t        ||      |d   |d   |d	   
      S 	 | j!                          d {   }t#        |d   |d   |d   |d	   
      S 7 h7 7 7 b# 1 d {  7  sw Y   rxY w7 =# t$        $ r t'        t(        j*                  d      d w xY ww)Nr6  zmultipart/form-datar   r   r  )rg  filesr|  r  fn_name)rg  r|  r  r  rg  zInvalid JSON body.rP  )r   r   rm   ro   r6  formr  r  r  StarletteUploadFiler  rN  readappendr+   r-   rd  r,   r!  r   r   r  )r   content_typer  rg  r  ry  r   r  vrN  contentss              rr   get_item_or_filez(App.create_app.<locals>.get_item_or_file  s     #??..~>L,,1H1H%2 "<<> . .T&*jjl .
U&ud3 #E
Q *585H I(1%(8 ;1#-a1D#E/0zzH56VVX~H$)LL(H1E$F9:DC5!$6; (/BC',~~H-2ZZ\'9H!LL(H)=>(-DI%.. .* /&D>!%n!5!%n!5 O	  !(/D2!&\%).%9%).%9 $Y	 =. 0> (:!. . . .: 0 !  '$*$?$?3    s   AH
GH
BG
%G
&AG
:G;G
H
%G&'H
G! !G"G!  H
G
G
H

GGGH
G! !&HH
z/component_serverz/component_server/c                  K    	|        d {   }j                   |j                     }|j                  }||v r||   }nj                         j                  |   }t        ||j                  d       }|t        |dd      st        t        j                  d      t        ||j                  g| d       ^}}t        j                  |      r ||  d {   S  || S 7 7 w)N_is_server_fnFzFunction not found.rP  )r   r  r|  r   r   r;  r  r   r   r  r9   rg  r  r  )
r   rj  r  r|  blockr  processed_inputr  r  r  s
           rr   component_serverz(App.create_app.<locals>.component_serverB  s      *'22D$$T%6%67E,,Lu$l+(//=d3Bz_e!D# & 9 90  #/	#Oa **2.111?++/ 3* 2s"   C'C#C	C'C%
C'%C'z/queue/status)rY  response_modelc                 \   K    j                         j                  j                         S wrl   )r   re  
get_statusr  s   rr   get_queue_statusz(App.create_app.<locals>.get_queue_statusf  s%      >>#**5577s   ),z/upload_progressc                    K   d	 fd}	 t        j                  t        j                         d       d {    t         ||      d      S 7 # t         j                  t        f$ r t        dd      cY S w xY ww)
Nc                 K   t        j                         }d}	 | j                          d {   rt        j	                         y |rt        j	                         y d}d}	 t        j                        rddi}d}n/t        j                        }d|j                  |j                  d}d	t        j                  |       d
 7 # t        $ r Y y t        $ ro t        j                  |       d {  7   t        j                         |z
  |kD  r4ddi}d	t        j                  |       d
 t        j                         }Y w xY ww)NFTr\  r]  rk  r  r<  )rk  	orig_name
chunk_sizer  r`  r  )ra  rb  rc  file_upload_statusesstop_trackingis_doner  rN  r  rd  ry   rA   r@   re  rf  )r   ri  r  rg  rh  r  r<  	upload_ids          rr   r  z?App.create_app.<locals>.get_upload_progress.<locals>.sse_streamp  sD    !%!2!2!4$44666,::9E,::9E%'N!%JA/77	B',foG&*G%9%=%=i%HF'/-3__.4.?.?'G
 !'tzz'':&;4@@+ 6* = ; A%mmJ777,,.?.P',k&:G$*4::g+>*?t"DD-1->->-@NAsM   +EC6E&A'C E	EE E;C><AEEEE   )r   zUpload not foundr  rr  rm  rn  ro  )re  wait_forr  
is_trackedTimeoutErrorr   r   )r  r   r  s   `  rr   get_upload_progressz+App.create_app.<locals>.get_upload_progressn  s      ADN&&(33I>   %7#.  ((,7 N();MMNs7   A>-A AA A>A &A;8A>:A;;A>z/uploadc           	     *  K   | j                   j                  d      }t        |xs d      \  }}|dk7  rt        dd      	 |rt        j                  |       j                         j                  }||nt        j                  }t        | j                   | j                         dd||r|nd |rt        nd       }|j                          d {   }g }g }g }|j!                  d      D ]]  }t#        |t$              st'        d      |j(                  r5t+        |j(                        j,                  }t/        j0                  |      }ndt3        j4                  d       }t+        j6                        |j8                  j;                         z  }|j=                  dd       	 t?        j@                  tC        tE        |            tG        |            }|jJ                  jM                          	 tO        jP                  |jJ                  j,                  |       |jU                  |       jV                  jY                  |       ` |r|j[                  t\        ||       |S 7 # t        $ r3}	d	|	j                  v rd
nd}
t        |	j                  |
      cY d }	~	S d }	~	ww xY w# tH        $ r}t        dd|       |d }~ww xY w# tR        $ r9 |jU                  |jJ                  j,                         |jU                  |       Y w xY ww)Nr6  r      multipart/form-datar}  Invalid content type.rP  i  )	max_files
max_fieldsmax_file_sizer  upload_progressmaximum allowed size  rr  r  z+File is not an instance of GradioUploadFiletmp   Tr  r  zInvalid file name: )/r   r   r!   r   r  trackr   r   rm  rn  rB   r3  parserD   r  r   getlistrm   rC   	TypeErrorrN  r   r  rO  !strip_invalid_filename_charactersr   	token_hexr   shar$  r  r   r  r.   ro   r4   r8   rc  closer   renamer  r  upload_file_setr  r  rI   )r   bg_tasksr  content_type_headerr   r  r   multipart_parserr  exccodeoutput_filesfiles_to_copy	locations	temp_filer&  r  r   destr  r  r   s                       rr   upload_filez#App.create_app.<locals>.upload_file  s     #*//"5"5n"E23F3L"MOL!55#<STTH(..y9 # 0 > >1>1JPTPXPX#8OONN$"#"/+4i$<E$84$  .3355
 LM#%I!\\'2 1	!)-=>#$QRR%% $Y%7%7 8 = =I'II)TD !2!21!5 67D !6!67)--:Q:Q:SS	t< ??%c)n57G7MD $$&+IIinn1148 ##D)&&**40=1> !!0-  Y 6% H4Cs($GGH, ( '$'2EdV0L  +!(()<)<=$$T*+s   A LBI- I*I- CL*1J,L6*K A
L*I- -	J)6(J$J)L$J))L,	K5KKL?LLLLz/startup-eventsc                    K    j                   sL j                         j                           j                         j                          d {    d _         yy7 w)NTF)r   r   run_startup_eventsrun_extra_startup_eventsr  s   rr   startup_eventsz&App.create_app.<locals>.startup_events  sP     // 335nn&??AAA/3, Bs   AAAAz
/theme.cssc                 N    t         j                         j                  d      S )Nztext/cssrn  )r   r   	theme_cssr  s   rr   rA  z!App.create_app.<locals>.theme_css  s     %S^^%5%?%?JWWrt   z/robots.txtc                 <     j                         j                  ryy)NzUser-agent: *
Disallow: /zUser-agent: *
Disallow: )r   r  r  s   rr   
robots_txtz"App.create_app.<locals>.robots_txt  s    ~~%%32rt   z	/pwa_iconz/pwa_icon/{size}c                  K   j                         }|j                  }|t        d      | t        |      S dd l}|j
                  j                  |      }|j                  | | f      }t        j                         }|j                  |d       |j                  d       t        t        j                  |j                               d      S w)Nr  rr  r   PNG)formatrd   rn  )r   r   r   r   	PIL.ImageImager  resizeioBytesIOsaveseekr   r  )sizer   r   PILimgimg_byte_arrayr  s         rr   pwa_iconz App.create_app.<locals>.pwa_icon  s      ^^%F!..L##44|#L11))...C**dD\*CZZ\NHH^EH2"$

>..01k s   CCz/manifest.jsonc                 v   j                   } t        | t              rt        |       } | 	dddddg}nY| j	                  d      rj                  d      ddddg}n0j                  dd      d	d
ddj                  dd      dd
ddg}t        j                         j                  xs d|dddd      S )Nzstatic/img/logo_nosize.svgr   zimage/svg+xml)srcsizesr  purposez.svgrR     )rN  192x192rd   i   512x512Gradioz./
standalone)r  icons	start_urldisplayzapplication/manifest+jsonrv  )	r   rm   r   ro   r   url_path_forrj   r   r  )r   r\  r  r   s     rr   manifest_jsonz%App.create_app.<locals>.manifest_json  s    
 "..L,-"<0#  <!& /#(	 &&v.  #//
;!& /#(	  #//
/E!* +#(	  #//
/E!* +#(	 "  NN,22>h"!%+ 7	 	rt   /monitoringc                   K   j                   st        dd      t        j                  | t         dj
                        }| dj                   }t        d| d       t        d	      S w)
NrB  Monitoring is not enabled.rP  ra  rt  /monitoring/z* Monitoring URL: z *zSee console for monitoring URL.)	enable_monitoringr   r&   r  r=   r   r   rA  r   )r   root_urlmonitoring_urlr  r   s      rr   analytics_loginz'App.create_app.<locals>.analytics_loginH  s     ++# #,H  #//(\5--H
 !)zc6G6G5HIN&~&6b9: ABBs   A.A1z/monitoring/summaryc                 T   K    j                         j                  j                  S wrl   )r   re  cached_event_analytics_summaryr  s   rr   r  zApp.create_app.<locals>._W  s      >>#**IIIs   %(z/monitoring/{key}c                  K   j                   st        dd      t        | j                        rdj                   d}j                  seddlm} ddlm} t        ||d	
       |j                  j                          j                         j                  j                  }||d<   d_        t        |t        j                        S t        dd      w)NrB  rc  rP  rd  z
/dashboardr   )rg  )demoF)r   r  rg  Trv  zInvalid key.)re  r   rG   r   r   gradio.monitoring_dashboardrg  rl  mount_gradio_appre  ra  r   event_analyticsr$   r   r  )ry  analytics_urlrg  	dashboard	analyticsr  r   s        rr   analytics_dashboardz+App.create_app.<locals>.analytics_dashboard[  s     ++# #,H  *#s/@/@A".s/@/@.A L--@M$Y]u $$**, # 0 7 7 G GI#,DL-1C*'%63H3H  $NKKs   CCz/process_recordingc           
     &  K   	 | j                   j                  d      }t        |xs d      \  }}|dk7  rt        dd      | j                  }t        |d      r|j                         j                  nd }||nt        j                  }t        | j                   | j                         dd	|
      }|j                          d {   }|j!                  d      }
|
rt#        |
d   t$              st        dd      |
d   }i }|j                  d      9|j                  d      (|j                  d      |d<   |j                  d      |d<   |j                  d      }|r"	 t'        j(                  t+        |            |d<   t/        j0                  ddt2              5 }|j4                  j7                  d       t9        j:                  |j4                  |       |j<                  d d d        t9        j>                  d      tA        ddtC        fd            S t/        jD                  dt2              d   }	 tG        ||       d {   \  }tA        |ddtC        fd            S 7 # t        $ r3}d|j                  v rdnd}	t        |j                  |	      cY d }~S d }~ww xY w# t&        j,                  $ r	 g |d<   Y Mw xY w# 1 sw Y   xY w7 # tH        $ r tA        ddtC        fd            cY S w xY ww) Nr6  r   r  r}  r  rP  r   r   
   )r  r  r   r"  r#  rr  videor   zNo video file providedremove_segment_startremove_segment_endzoom_effectsFz.mp4)deletesuffixdirffmpegre   zgradio-screen-recording.mp4c                       g      S rl   r   cleanup_files
input_paths   rr   <lambda>z;App.create_app.<locals>.process_recording.<locals>.<lambda>      mZL6Q rt   )r   rN  r8  z_processed.mp4)r{  r|  c                             S rl   r   )r  
temp_filess   rr   r  z;App.create_app.<locals>.process_recording.<locals>.<lambda>  s    mJ6O rt   c                       g      S rl   r   r  s   rr   r  z;App.create_app.<locals>.process_recording.<locals>.<lambda>  r  rt   )%r   r   r!   r   r  r  r   r   rm  rn  rB   r3  r(  rD   r  r   r)  rm   rC   rd  r  ro   r  tempfileNamedTemporaryFileDEFAULT_TEMP_DIRrc  rM  shutilcopyfileobjr  whichr   r"   mkstemprJ   r!  )r   r2  r   r  r  r   r3  r  r4  r5  video_files
video_fileparamszoom_effects_json
input_fileoutput_pathprocessed_pathr  r  r  s                    @@rr   process_recordingz)App.create_app.<locals>.process_recordingt  s    H&-oo&9&9.&I#"67J7Pb"Qa#99'C@WXXkk sL1 NN$22 
 2?1JPTPXPX#8OONN$!"/$  .3355
 ,,w/KjQAQ&R#<TUU$QJF/0<HH12>15:P1Q-./3xx8L/M+, $ 8 0-1ZZ<M8N-OF>* ,,V1A -$$Q'"":??J?'__
- ||H%-#*:-.QR	  #**'-=K3LV4 .*
 $"*:-.OP	 e 6% H4Cs($GGH, ++ 0-/F>*0- -(.  #*:-.QR	 s   LCI: 	I7
I: BL&!J9 L#AK+ALK& K$"K& 6L7I: :	J6(J1+J6,L1J66L9KLKLK!L$K& &%LLLLvibe_edit_historyr&  historyc                    | j                         sy| j                  d      }t        |      |k  r| S || d }t        |      dkD  r6|d   j                  d      r|d   }nd|d   z   }|dd D ]
  }|d|z   z  } |S y)zLLimit chat history in the prompt to the last max_pairs user-assistant pairs.r   
User: Nr   zUser: r   )r  rX  r  r6  )r  	max_pairsuser_messagesrecent_messagesresultrk  s         rr   limit_chat_historyz*App.create_app.<locals>.limit_chat_history  s    ==?#MM*5M=!Y.+YJK8O?#a'"1%00:,Q/F%(::F*12. /Cj3..F/ rt   z<\|[^>]*\|>z3<\|start\|>assistant<\|channel\|>final<\|message\|>z	<\|end\|>z9<\s*reasoning\s*>\s*(?P<body>.*?)\s*<\s*/\s*reasoning\s*>z!<\s*think\s*>.*?<\s*/\s*think\s*>c                   | s| S j                  |       }|rI| |j                         d  }j                  |      }|r|d |j                          }|j                         S j	                  d|       }|j                         S )Nr   )searchrb  ra  r  sub)rawmtextm_endcontrol_token_reend_refinal_start_res       rr   clean_out_markersz)App.create_app.<locals>.clean_out_markers  s|    
%%c*A15579~d+%++-0Dzz|##''C0D::<rt   c                (    j                  d|       S )z/Remove any <think> ... </think> blocks entirelyr   )r  )r  think_block_res    rr   strip_think_blocksz*App.create_app.<locals>.strip_think_blocks  s    !%%b$//rt   c                `   g }t               }j                  |       D ]K  }|j                  d      j                         }|s%||vs*|j	                  |       |j                  |       M dj                  |      j                         }j                  d|       j                         }||fS )z
            Extract all <reasoning>...</reasoning> and code. If multiple, concatenate with blank lines, de-duping exact copies.
            rj  r`  r   )r   finditergroupr  r  r  joinr  )r  reasoning_chunksseenr  rj  reasoning_text	code_textreasoning_block_res          rr   split_reasoning_codez,App.create_app.<locals>.split_reasoning_code  s      "5D'006 #wwv,,.D,$++D1HHTN	# $[[)9:@@BN*..r48>>@I!9,,rt   )InferenceClientz/vibe-edit/z
/vibe-editc                  	K   j                   st        dd      ddlm} t	        |      5 }|j                         }d d d        t        j                  d      }| dz  }t	        |d      5 }|j                         d d d        d	   |<   d
} d	         }d d| j                   d|r|nd d}t               }	j                  dd|	dd|dgd      j                  d   j                  j                  }|t        dd       |      } |      }d	xx   d| j                   d| dz  cc<    |      \  }
}d|v r>|j                  d      t!        d      z   }|j#                  d|      }|dk7  r||| n||d  }|j%                  d      }|j%                  d      }t'        t)        j*                  ||d            }d}d}|D ]S  }|j-                  d       r|j-                  d!      s|d"z  }+|j-                  d#      s=|j-                  d$      rO|d"z  }U t	        |d      5 }|j                  |       d d d        |||d%|
d&S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   ,xY ww)'NrB  6Vibe editor is not enabled. Use --vibe flag to enable.rP  r   GRADIO_WATCH_DEMO_PATHr   .pywr  r   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

History:
zNo chat history.ru  openai/gpt-oss-120br  rolerq   rS  '  modelr  
max_tokensr  Error generating coder  z
Assistant: z
```python
z
```T)keepends)n+z+++r   r  z---)lines_addedlines_removed)hash
diff_stats	reasoning)	vibe_moder   gradio.http_serverr  r  r  r   r,  r  promptload_system_promptchat_completionchoicesr  rq   indexr  find
splitlinesr  difflibunified_diffr6  )rj  r  r  original_codesnapshot_hashsnapshot_filerq   limited_historyr  system_promptr  ra  rb  original_lines	new_linesdiffr  r  liner   chat_historyr  hash_to_chat_historyinference_clientr  r  r  vibe_edit_history_dirs                      rr   	vibe_editz!App.create_app.<locals>.vibe_edit"  s     ### #S 
 B,- ) !) $--b1M1}oS4IIMmS) 'Q&' 3?y2I /G0i1HIO     $); < =F /0M 00/!)mD!'F;  % 1     #<STT'0G(1G#$++mG9TV'WW#!5g!>Iw'm4s=7IIll7E203r	'%,wuv +55t5DN**D*9I,,^Y!LMDKM '??3'0F1$K__S)$//%2H!Q&M	' ,c2 !a ! &#.%2 ' S) )' '@! !sX   +J I1J 0I'FJ J $J 7I4	J I$J 'I1,J 4I=9J z/undo-vibe-edit/z/undo-vibe-edit.)embedc                  K   j                   st        dd      ddlm} |  dz  }|j	                         st        dd      t        |      5 }|j                         }d d d        t        |d	      5 }|j                         d d d        j                  | d
      d<   ddiS # 1 sw Y   HxY w# 1 sw Y   .xY ww)NrB  r  rP  r   r  r  r  zSnapshot not foundr  r   r  rw  T)	r  r   r  r  r  r  r  r  r   )	r  r  r  r  saved_contentr   r  r  r  s	        rr   undo_vibe_editz&App.create_app.<locals>.undo_vibe_edit  s      ### #S 
 B1tfCL@M '')#<PQQ m$ ) !) ,c2 'a&' ';&>&>tR&HL#t$$) )' 's6   ACB+$C8B7
!C+B40C7C <Cz/vibe-code/z
/vibe-codec                 6  K   j                   st        dd      ddlm}  	 t	        |       5 }|j                         }d d d        diS # 1 sw Y   xY w# t        $ r t        dd      d t        $ r}t        d	d
t        |             |d }~ww xY ww)NrB  r  rP  r   r  r5  r  zDemo file not foundr  zError reading file: )	r  r   r  r  r  r  r  r!  ro   )r  r  r5  r'  r   s       rr   get_vibe_codez%App.create_app.<locals>.get_vibe_code  s      ### #S 
 B01 $Q668D$~%$ $ % # #,A  # #.B3q6(,Ks?    BA A A BAA B7BBBc                "  K   j                   st        dd      ddlm} 	 t	        |d      5 }|j                  | j                         d d d        ddiS # 1 sw Y   xY w# t        $ r}t        d	d
t        |             |d }~ww xY ww)NrB  r  rP  r   r  r  rw  Tr  zError writing file: )	r  r   r  r  r  r  r5  r!  ro   )rj  r  r  r'  r   s       rr   update_vibe_codez(App.create_app.<locals>.update_vibe_code  s      ### #S 
 B0#6 '!GGDII&'!4((' '  # #.B3q6(,Ks?    BA$ AA$ BA!A$ $	B-BBBz/vibe-starter-queries/z/vibe-starter-queriesc                   K   j                   st        dd      ddlm}  t	        |       5 }|j                         }d d d        d d}t        d	      }	j                  d
d|dd|dgd      j                  d   j                  j                  }|t        dd       
|      } |      }|j                  d      }d|iS # 1 sw Y   xY ww)NrB  r  rP  r   r  z
You are a prompt generator for a gradio vibe editor. Given the following existing code, return a list of starter queries that can be used to generate a new code.
Existing code:
```python
z
```
T)starter_queriesr  r  r  rS  r  r  r  r  ru  r  )r  r   r  r  r  r  r  r  r  r  rq   rX  )r  r  r5  r  r  rq   r  r   r  r  r  s          rr   get_vibe_starter_queriesz0App.create_app.<locals>.get_vibe_starter_queries  s     ### #S 
 B,-  vvx   	F /tDM 00/!)mD!'F;  % 1     #<STT(1G'0G%mmD1O "? C   s   +CC
BC
CCc           
         | D ]9  }	 |r4t         j                  j                  |      rt        j                  |       ; y # t        $ r$}t        d| dt        |              Y d }~ed }~ww xY w)NzError cleaning up file z: )r   r   r  unlinkr!  rA  ro   )r  rc  r'  s      rr   r  z%App.create_app.<locals>.cleanup_files  sh     FFt 4		$F ! F3D6CF8DEEFs   6A  	A-	A((A-r   ro  )r   rp  r   r  )rS  ro   )r   rp  r   r  )r   rp  r  r   )r   rp  rS  ro   r  bool)r   ro   rl   )r  ro   r$  dict[str, Any]r  r  )r   rp  rS  ro   r  ro   r  ro   )r  ro   )r   )r   rp  r  ro   )
r  ro   r%  zLiteral['client', 'server']r  ro   r&  ro   r'  rp  )r  ro   )r]  ro   r   rp  )ri  ro   rj  r0   r   rp  )ri  ro   )r  ro   r{  r?  r|  r?  )
r  ro   r{  r?  r|  r?  r  ro   r  ro   )r   ro   r   rp  )rj  r2   )r  ro   r   rp  r  r   r~  ro   )r  ro   rj  r0   r   rp  r~  ro   )r  ro   rj  r3   r   rp  r~  ro   )rj  r0   r   rp  r~  ro   )rj  r*   )r   rp  ri  ro   )r   rp  r  ro   )r   rp  r  ro   r  z$Callable[[EventMessage], str | None])r   rp  r   z7Union[ComponentServerJSONBody, ComponentServerBlobBody])r  ro   r   rp  )r   rp  r1  r   r  r  )rN  
int | None)ry  ro   )r%  )r  ro   r  r?  r   ro   )r  ro   r   ro   )r  ro   r   ro   )r  ro   r   ztuple[str, str])rj  r6   )r  ro   )rj  r5   )'r   rj   r   r(  delete_cacherH   r   r  launch_mcp_on_sser   r   r=   r   add_middlewarer>   r(   
middlewarer   r  r   expects_oauthr<   r  headr   rL   r   r   r  r  recompile
IGNORECASEDOTALLr  huggingface_hubr  r   include_router)Nr   r%  r   r-  ssr_moder  r&  r  routerrD  rT  rV  rX  rq  r  r  r  r  pagesetr  r  r  r
  r,  r/  r1  r@  r  r  r  r  r  r  r  r  r  r  r  r  r;  r?  rA  rC  rR  r`  rh  rs  r  r  r  r  r  r  r  r   r  r  r  r  r  r  rc  r  rJ  r  r  r  r  r  r  r  r  r  r  r  r  r  r  sN   `                                                     @@@@@@@@@@@@@@@@@@@@@@@@rr   
create_appzApp.create_app  s)     %2
6G**6:zJ**:l!8NN:t,"
/;"

: L/LZLtL  !!33CfFVFVW*-&!/[I*m 	 	
 ^^F#  (   $  D 
G		H		) 
 
	) 
N	#	O	$$+,<$= 		 
% 
$		 
H		I		C 
 
	C 
I		J		7 
  
	7 
M1E0F	G	$	 
H	@ 
(		)	MTY(	V$(	V1J(	V 
 
(	Vb ::!cjj&>&> WWY $$45$( (   "    : 
&	'	 
(		< || 	"G1:DrzD!	" HL	/	/$2	/:D	/8 
#l	3	\	2   01	U	$U	U	 U	 	U	 
3 
4U	n 
(	)	 
*	( 
HGK,@+A	B	G7;+?*@	A	  
B 
C	  
O7;3G2H	I_	 
J_	B 
7;+?*@	A	'+*>)?	@	2 	2 
A 
B	2& 
&	'	- 
(	- 
M	N;	7;	74;	7 ;	7 	;	7
 !;	7 
O;	7z 
&	'	, 
(	, 
	 	9 
!	9 
-W[=Q<R	S	,GK<P;Q	R	 
S 
T	$ 
/w{?S>T	U	.gk>R=S	T>	 
U 
V>	@ 
)	*	& 
+	& 
/	0	& 
1	& 
O	P	 
Q	8 
T	U	R	R$'	R7:	RHK	RRU	R 
V	R2 
O	P	6 
Q	62 
'w{7K6L	M	- 
N	- 
Y		X		% 
 
 	% 
/	0
 $$45	E	QE	Q$E	Q .E	Q 	E	Q 
1E	QP 
&gk6J5K	L	'w{7K6L	M	&gk6J5K	L	'w{7K6L	M
 $$45	+	*+	*+	* %+	* 	+	* 
N 
M 
N 
M+	*Z 
'w{7K6L	M	(8L7M	N
 $$45		I	I#	I %	I 		I 
O 
N	I 
]'+2F1G	H $$45
	D
	D$
	D 
	D 
I
	D	*	*$	* 	*> 
Y		% 
 	%0 
1AU@V	W	K$	K	K 
X	K0 
M1E0F	G	O$	O	O 
H	Od	$d	d	 >d	L3	 $3	 D3	 j 
!+./ 
 

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

	,$	,	

	

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


	8


	8 
&	'-	 
(-	^ 
Ygk.B-C	D %)E	 $E	 %E	  "E	  
EE	 N 
%	&	 
'	 
L1B	C	.?	@	X 
A 
D	X 
/@	A	3 
B	3 
		#	$	 
% 
	, 
!	"2	 
#2	h 
gk.B-C	D	C 
E	C 
&	'	J 
(	J 
$	%	L 
&	L0 
)9M8N	OW	$W	 
PW	r !%%5 69L L##T4#@!2!	0 ::n5BBMM
 L"--8ZZHMMBII%
 0"--"))2K

	 	0	-" 7.0	]	#	\	"Y	 Y	 
# 
$Y	v 
'	(	&	'-1#T-B 	% 	% 
( 
)	%2 
M	"	L	!	 
" 
#	, 
]	#	\	"	 
# 
$	$ 
-	.	,	-,	 
. 
/,	\	F 	6"
rt   rl   )r   .Callable[[fastapi.Request], str | None] | None)r1  r   )r   rp  r   ro   r   r?  r   r?  r   ro   r   ro   r   r   )r   gradio.Blocksr   None)r   r	  )r   r	  r%  r  r  bool | None)NNTFN)r   r	  r%  dict[str, Any] | Noner   r  r-  r  r  r  r  r  r   r   )r   r   r   __doc__r=  r   r   AsyncClientr   rE   r   r   r   r   r   r  r
  r(  r  __classcell__)r   s   @rr   r   r      sV    H KO #G #J U F (K '
 '
'
 '
 	'

 '
 '
 
'
 '
R- 
"!
  #'))")  ) )V  -1JN "&]])] H] 	]
 ]  ] 
] ]rt   r   c                    d}| rd}	 t        j                         5 }|j                  d      }|j                  }d d d        |z   |z   }|S # 1 sw Y   xY w# t        $ r d}Y #w xY w)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. Make sure it's easy to parse. Use markdown formatting when it makes sense, including bullet points if there are multiple changes.


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()
a  
        You are a prompt generator for a gradio vibe editor.

        Given python code of a gradio app, return a list of starter queries that can be used to generate new code.
        Make sure the queries are short, useful and actually possible with Gradio.
        The queries should be really simple and easy to understand.
        You should respond with at most three queries, each on a new line. Do not include any other text.
        Make sure the features you suggest are actually supported by Gradio, and documented in the docs section below.
        Never suggest a query with more than one gradio feature or concept.
        You may suggest queries that are not related to Gradio, but they must be related to the existing code and app. Never suggest queries that require external packages or libraries other than gradio.
        Don't suggest adding a clear button if the app is an Interface, because Interface already has a clear button.

        Here's an example of a gradio app:

        ```python
        import gradio as gr

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

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

        demo.launch()
        ```

        Here's an example of a valid response:
        Add a title to the app
        Add examples
        Rewrite this app using Blocks

        Here's an example of another valid response:
        Add another textbox for name
        Change the theme
        Greet the user in many languages

        zhttps://www.gradio.app/llms.txtr   )r   Clientr   r  r!  )r  prompt_rulesr   rC  r  s        rr   r  r  	  s    L> #H\\^ 	*vzz"CDH$MMM	*
 !=0<?M	* 	*  s'   A AA AA A&%A&c                   |dk(  rt        j                  d      t        j                  |      rt        j                  d      	 t	        t        j                  | |            }|j                         rt        j                  d      |j                         st        j                  d      t        |      S # t        $ r}t        j                  d      |d}~ww xY w)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}  rB  Nr  )fastapir   r&   rQ  r   r   r  r8   rS  r  ro   )r   r   fullpathr'  s       rr   r  r  V	  s     rz##C((''-##C((0	489 ##C((??##C((x=  0##C(a/0s   B: :	CCCc                B   g }g }| D ]  }t        j                  |      xs d}|j                  d      }|D ]<  }d|v s|j                  |j                  d      d   j                  d      d          > |j                  |d   j                  d      d           ||fS )	Nr   ru  zvalue (r   )r   r   r  )r  getdocrX  r  )cls_setdocsettypesclsdoc	doc_linesr  s          rr   	get_typesr  i	  s    FE 3nnS!'RIIdO	 	EDD TZZ	215;;C@CD	E 	il((-b123 5=rt   T)r   rO  r   r   rF  rE  r   r  r   r  r@  r   re  pwai18nr  themecss	css_pathsjsr  
head_pathsc               8   ||dk7  rt        j                  d       d|_        |g d}||_        t	        j
                  |      |_        |j                         |_        |j                          ||_
        ||_        ||_        ||_        |||_        |||_        ||	t!        d      |r:t#        |      s/t%        |d   t&              st%        |d   t(              s	|g|_        n||_        ||_        ||_        |xs g |_        |xs g |_        ||_        t%        |j0                  t(              st!        d      t%        |j2                  t(              st!        d      |
|
|_        ||n&t9        j:                  d	d
      j=                         dk(  |_        |j>                  rzt8        j@                  jC                  dtE                     |_#        ||_$        ||_%        tM        |jH                  |jJ                  |jF                        \  |_$        |_'        |_%        t	        jP                  |      |_)        |xs d|_*        |xs d|_+        |xs d|_,        |xs g |_-        |xs g |_.        |j_                          |ja                          tb        je                  |||	|j>                  |      | jf                  jh                  tj        jl                  dfd       }|| jf                  _4        to        d|       | jq                  |       | S )a_  Mount a gradio.Blocks to an existing FastAPI application.

    Parameters:
        app: The parent FastAPI application.
        blocks: The blocks object we want to mount to the parent app.
        path: The path at which the gradio application will be mounted, 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.
        footer_links: The links to display in the footer of the app. Accepts a list, where each element of the list must be one of "api", "gradio", or "settings" corresponding to the API docs, "built with Gradio", and settings pages respectively. If None, all three links will be shown in the footer. An empty list means that no footer is shown.
        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.
        theme: A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
        css: Custom css as a code string. This css will be included in the demo webpage.
        css_paths: Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.
        js: Custom js as a code string. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags.
        head: Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
        head_paths: Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.
    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.
    r5  zThe 'favicon_path' parameter is set but will be ignored because 'path' is not '/'. Please add the favicon directly to your FastAPI app.F)apirY   settingsz^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_PATH)r   server_port	node_pathr   )r%  r   r  r  c                 K    |       4 d {   }j                   j                        4 d {    j                         j                          j                         j	                          d {    | d d d       d {    d d d       d {    y 7 7 p7 .7 # 1 d {  7  sw Y   +xY w7 "# 1 d {  7  sw Y   y xY wwrl   )r  lifespan_contextr   r=  r>  )r  r  
gradio_appold_lifespans     rr   new_lifespanz&mount_gradio_app.<locals>.new_lifespan
  s     
 	 	!((99*E  %%'::< ++-FFHHH 	 	 	H   	 	 	 	s   CB#C CB%CA B+8B'9	B+CB)CCC C%C'B+)C+B=	1B42B=	9C CCC	CCnew)r  r   )9warningswarndev_modefooter_linksr   _parse_file_sizer   r#  r$  validate_queue_settingsr:  r,  r   re  r   r  r   r   rm   tupler  r   rO  r   rF  rE  r  r   r   r   r  r  r  r   rU   r-  r@  r   r;   r3  	get_themer"  r#  r%  r  r&  r$  _set_html_css_theme_variablestranspile_to_jsr   r  r  r/  r  r   rA  mount) r  r   r   r   r,  r7  r%  r   rO  r   r   rF  rE  r   r  r   r  r@  r   re  r   r!  r  r"  r#  r$  r%  r  r&  r2  r0  r1  s                                  @@rr   rn  rn  v	  s   X DCKC	

 FO4&F 11-@F**,FM
""$#F$F$F0F

#O7l
 	
 	47E*47D)f&F&F(.BF(.BF"Ff**D1IJJf**D1IJJ$  	YY('288:fD O ::>>*<moN"2$"33",, ** 	G!4f6F ??5)FLFJbFI*"FK"(bF BF
((*
'   J ::..L## $ #/CJJ	%IIdJJrt   )z	theme.cssz
robots.txtrR  zmanifest.jsonr  r  r  r$  staticassetszfavicon.ico
gradio_api
monitoring)F)r  r  )r   r.   r   r4   r   ro   )r  z
list[type])r9  i  NN)<r  fastapi.FastAPIr   r	  r   ro   r   ro   r,  r?  r7  zBlist[Literal['api', 'gradio', 'settings'] | dict[str, str]] | Noner%  r  r   z9Callable | tuple[str, str] | list[tuple[str, str]] | NonerO  r  r   r  r   r  rF  list[str] | NonerE  rD  r   r  r  r  r   zstr | int | Noner  r  r@  r  r   r  re  r  r   r  r!  zI18n | Noner  r  r"  zTheme | str | Noner#  r  r$  (str | Path | Sequence[str | Path] | Noner%  zstr | Literal[True] | Noner  r  r&  rE  r   rC  )r  
__future__r   re  r  r   importlib.resources	importlibr  rJ  rd  rm  r  r   r  r   r  ra  r  r4  collections.abcr   r   r   pathlibr   r  r   r  typingr	   r
   r   r   r   r  r   r   rx   r   r   r   r   r   r   r   fastapi.responsesr   r   r   r   r   r   fastapi.securityr   fastapi.templatingr   gradio_clientr   rO  gradio_client.documentationr   gradio_client.utilsr   jinja2.exceptionsr    python_multipart.multipartr!   starlette.backgroundr"   starlette.datastructuresr#   r  starlette.responsesr$   rY   r%   r&   r'   gradio.brotli_middlewarer(   gradio.contextr)   rT  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   rI   gradio.screen_recording_utilsrJ   gradio.server_messagesrK   rL   rM   rN   rO   rP   rQ   gradio.state_holderrR   gradio.themesrS   Themegradio.utilsrT   rU   rV   rW   gradio.blocksrX   r  r  r  r  init	resourcesr  joinpathas_posixSTATIC_TEMPLATE_LIBr  r  r  r;  r  r   ro   
gettempdirr  BaseDefault
MonochromeSoftGlassOriginCitrusOceanr  rh   __annotations__rj   r   rZ   envfiltersr  LimitsTimeoutr   r  r   r  r  r  rn  r<  )r  s   0rr   <module>ry     s  U #      	    	   
    = =  %         7 . / 0 - . ; / F 0   6 "    6 '  &    D   , -  #  	   	 h'00=FFH  h'X)*XZ	 h'X)*XZ	 
  ::>>"34 				(*9  		%	 	vv FFAI%!  ?\ ?2 &9:	$,	  j !			5<<"$ EMM$
 *+ N ' N l@L^&
 

 ! 	(,m GK#FJ &*&*#&* #' %)" $:>%);?Am	mm m 	m
 m 	Km &m Dm m Dm m $m  $!m" #m$ %m& $'m( )m* !+m, -m. #/m0 
1m2 3m4 5m6 7m8 
9m: 8;m< 	#=m> ?m@ 9AmB Cm m`oK%s   "Q-