U
    ARd7                     @   s$  d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZm	Z	m
Z
 d dlZd dlmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZm Z m!Z! d d
l"m#Z#m$Z$m%Z% ee&Z'dej(ddddej(dddej(dddd Z)dZ*e#ddddZ+e,ddddZ-ddddZ.dddd Z/e,e	e, dd!d"d#Z0e#ddd$d%Z1ddd&d'Z2ddd(d)Z3e,ddd*d+Z4e5dd,d-d.Z6e,ddd/d0Z7ee,ef dd1d2d3Z8ee,ef dd1d4d5Z9e,dd6d7d8Z:e,e
e, e	e, ee,ef dd9d:d;Z;dS )<    N)Path)AnyDictListOptional)configenv_util	file_utilnet_utilsecretsurl_utilutilversion)CONFIG_FILENAMES)MIN_GIT_VERSIONGitRepo)
get_loggerinvalidate_pages_cache)report_watchdog_availability	watch_dir
watch_file)Serverserver_address_is_unix_socketserver_utilz
  %(new_version)s

  See what's new at https://discuss.streamlit.io/c/announcements

  Enter the following command to upgrade:
  %(prompt)s %(command)s
z(A new version of Streamlit is available.blueTfgbold$r   zpip install streamlit --upgrader   )Znew_versionpromptcommandi   @)serverreturnc                    s^   t d  fdd}ttj| ttj| tjdkrLttj| nttj| d S )NzSetting up signal handlerc                    s       d S N)stop)Zsignal_numberZstack_framer$    ;/tmp/pip-unpacked-wheel-b9et7o5g/streamlit/web/bootstrap.pysignal_handlerC   s    z._set_up_signal_handler.<locals>.signal_handlerwin32)	LOGGERdebugsignalSIGTERMSIGINTsysplatformZSIGBREAKSIGQUIT)r$   r+   r)   r(   r*   _set_up_signal_handler@   s    

r5   )main_script_pathr%   c                 C   s   t jdtj|  dS )zAdd the script's folder to the sys path.

    Python normally does this automatically, but since we exec the script
    ourselves we need to do it instead.
    r   N)r2   pathinsertosdirname)r6   r)   r)   r*   _fix_sys_pathO   s    r;   r%   c                  C   s:   t dr6zddl} | d W n tk
r4   Y nX dS )a  Set Matplotlib backend to avoid a crash.

    The default Matplotlib backend crashes Python on OSX when run on a thread
    that's not the main thread, so here we set a safer backend as a fix.
    Users can always disable this behavior by setting the config
    runner.fixMatplotlib = false.

    This fix is OS-independent. We didn't see a good reason to make this
    Mac-only. Consistency within Streamlit seemed more important.
    zrunner.fixMatplotlibr   NZAgg)r   
get_option
matplotlibZuseImportError)r>   r)   r)   r*   _fix_matplotlib_crashX   s    
	r@   c                  C   sZ   t jrVtjdkrVzddlm} m} W n tk
r8   Y nX tt	 | krVt
|  dS )a/  Set default asyncio policy to be compatible with Tornado 6.

    Tornado 6 (at least) is not compatible with the default
    asyncio implementation on Windows. So here we
    pick the older SelectorEventLoopPolicy when the OS is Windows
    if the known-incompatible default policy is in use.

    This has to happen as early as possible to make it a low priority and
    overridable

    See: https://github.com/tornadoweb/tornado/issues/2608

    FIXME: if/when tornado supports the defaults in asyncio,
    remove and bump tornado requirement for py38
    )      r   WindowsProactorEventLoopPolicyWindowsSelectorEventLoopPolicyN)r   Z
IS_WINDOWSr2   version_infoasynciorD   rE   r?   typeZget_event_loop_policyZset_event_loop_policyrC   r)   r)   r*   _fix_tornado_crashu   s    rI   )r6   argsr%   c                 C   s   ddl }| gt| |_dS )ztsys.argv needs to exclude streamlit arguments and parameters
    and be set to what a user's script may expect.
    r   N)r2   listargv)r6   rJ   r2   r)   r)   r*   _fix_sys_argv   s    rM   c              
   C   s   t | j t| j t| j t  t  zt  W n0 t	k
rf } zt
jd|d W 5 d }~X Y nX dd }t | d S )Nz Failed to load secrets.toml file)exc_infoc                  S   s\   t drd S t dr$t d} n$t drDt r8d S t d} nd} tt|  d S )Nserver.headlessbrowser.serverAddressserver.address	localhost)r   r=   is_manually_setr   r   Zopen_browserr   get_url)addrr)   r)   r*   maybe_open_browser   s    


z,_on_server_start.<locals>.maybe_open_browser)_maybe_print_old_git_warningr6   "_maybe_print_static_folder_warning
_print_urlis_running_hellor   _print_new_version_messager   Zload_if_toml_exists	Exceptionr-   errorrG   Zget_running_loopZ	call_soon)r$   exrV   r)   r)   r*   _on_server_start   s    


 r_   c                   C   s   t dtjd< dS )z_Sets MAPBOX_API_KEY environment variable needed for PyDeck otherwise it will throw an exceptionzmapbox.tokenZMAPBOX_API_KEYN)r   r=   r9   environr)   r)   r)   r*   _fix_pydeck_mapbox_api_warning   s    ra   c                   C   s   t  rtt d S r&   )r   Zshould_show_new_version_noticeclicksechoNEW_VERSION_TEXTr)   r)   r)   r*   r[      s    r[   c                 C   sh   t drdt| }tj|s8tjd| ddd n,t	|}|t
krdt dd tjddd dS )	z7Prints a warning if the static folder is misconfigured.zserver.enableStaticServingzGWARNING: Static file serving is enabled, but no static folder found at zJ. To disable static file serving, set server.enableStaticServing to false.yellowr    FzVWARNING: Static folder size is larger than 1GB. Static file serving has been disabled.N)r   r=   r	   Zget_app_static_dirr9   r7   isdirrb   rc   Zget_directory_sizeMAX_APP_STATIC_FOLDER_SIZEZ
set_option)r6   Zstatic_folder_pathZstatic_folder_sizer)   r)   r*   rX      s    



rX   )rZ   r%   c                 C   s  | r
d}nd}g }t dr4dtt dfg}nt dr\t s\dtt dfg}nt rtdt dfg}n|t drt }|r|dt|f t	 }|r|d	t|f n0d
tdfg}t }|r|dt|f t
d t
jd| ddd t
d |D ]\}}t|| qt
d | rt
d t
jddd t
jddd t
d t
d t
d t
d d S )Nz9Welcome to Streamlit. Check out our demo in your browser.z4You can now view your Streamlit app in your browser.rP   URLrQ   zUnix SocketrO   zNetwork URLzExternal URLz	Local URLrR    z  %sr   Tr   z5  Ready to create your own Python apps super quickly?z  Head over to F)nlzhttps://docs.streamlit.ior!   z  May you create awesome apps!)r   rS   r   rT   r=   r   r
   Zget_internal_ipappendZget_external_iprb   rc   r   Z	print_url)rZ   Ztitle_messageZ
named_urlsZinternal_ipZexternal_ipZurl_nameurlr)   r)   r*   rY      sT    








rY   c                 C   s   t | }| s|jdk	r|jtk rddd |jD }ddd tD }td tjddd	d
 td tjd| d| ddd tjddd tjddd dS )zIf our script is running in a Git repo, and we're running a very old
    Git version, print a warning that Git integration will be unavailable.
    N.c                 s   s   | ]}t |V  qd S r&   str.0valr)   r)   r*   	<genexpr>.  s     z/_maybe_print_old_git_warning.<locals>.<genexpr>c                 s   s   | ]}t |V  qd S r&   rn   rp   r)   r)   r*   rs   /  s     ri   z  Git integration is disabled.re   Tr   z  Streamlit requires Git z or later, but you have r    z>  Git is used by Streamlit Cloud (https://streamlit.io/cloud).z,  To enable this feature, please update Git.)r   Zis_validZgit_versionr   joinrb   rc   )r6   repoZgit_version_stringZmin_version_stringr)   r)   r*   rW   $  s*    

rW   )flag_optionsr%   c                 C   s$   dd |   D }tjd|d dS )a;  Load config options from config.toml files, then overlay the ones set by
    flag_options.

    The "streamlit run" command supports passing Streamlit's config options
    as flags. This function reads through the config options set via flag,
    massages them, and passes them to get_config_options() so that they
    overwrite config option defaults and those loaded from config.toml files.

    Parameters
    ----------
    flag_options : Dict[str, Any]
        A dict of config options where the keys are the CLI flag version of the
        config option names.
    c                 S   s&   i | ]\}}|d k	r| dd|qS )N_rm   )replace)rq   namerr   r)   r)   r*   
<dictcomp>N  s   
 z'load_config_options.<locals>.<dictcomp>T)Zforce_reparseoptions_from_flagsN)itemsr   Zget_config_options)rv   r{   r)   r)   r*   load_config_options?  s    r}   c                    s0    fdd}t D ]}tj|rt|| qd S )Nc                    s   t   d S r&   )r}   _pathrv   r)   r*   on_config_changedZ  s    z3_install_config_watchers.<locals>.on_config_changed)r   r9   r7   existsr   )rv   r   filenamer)   r   r*   _install_config_watchersY  s    r   )main_script_path_strr%   c                 C   s:   t d ddd}t| }|jd }tt ||ddd d S )N)r   r%   c                 S   s
   t   d S r&   r   r~   r)   r)   r*   _on_pages_changedc  s    z1_install_pages_watcher.<locals>._on_pages_changedZpagesz*.pyT)Zglob_patternZallow_nonexistent)ro   r   parentr   )r   r   r6   Z	pages_dirr)   r)   r*   _install_pages_watcherb  s    
r   )r6   command_linerJ   rv   r%   c                    s`   t |  t  t  t| | t  t| t|  t| | dd fdd}t	|  dS )zuRun a script in a separate thread and start a server for the app.

    This starts a blocking asyncio eventloop.
    Nr<   c                      s.      I d H  t  t   jI d H  d S r&   )startr_   r5   stoppedr)   r(   r)   r*   
run_server  s    zrun.<locals>.run_server)
r;   r@   rI   rM   ra   r   r   r   rG   run)r6   r   rJ   rv   r   r)   r(   r*   r   q  s    


r   )<rG   r9   r/   r2   pathlibr   typingr   r   r   r   rb   Z	streamlitr   r   r	   r
   r   r   r   r   Zstreamlit.configr   Zstreamlit.git_utilr   r   Zstreamlit.loggerr   Zstreamlit.source_utilr   Zstreamlit.watcherr   r   r   Zstreamlit.web.serverr   r   r   __name__r-   stylerd   rg   r5   ro   r;   r@   rI   rM   r_   ra   r[   rX   boolrY   rW   r}   r   r   r   r)   r)   r)   r*   <module>   sZ   (
  	 	$>	
