a
    d!!                  
   @  s4  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m	Z	 ddl
Z
ddlZddlmZ ddlmZ ddlmZ e	rddlmZ eed	d
ZeeddZeddZdZG dd dejZddddddZddddddZd*dddddddddd d!Zd"dd"d"d#d$d%Zd"d&d'd(d)ZdS )+z^
Defines helper methods useful for setting up ports, launching servers, and
creating tunnels.
    )annotationsN)TYPE_CHECKING)ServerFailedToStartError)App)Tunnel)BlocksZGRADIO_SERVER_PORTZ7860ZGRADIO_NUM_PORTSZ100ZGRADIO_SERVER_NAMEz	127.0.0.1z(https://api.gradio.app/v2/tunnel-requestc                   @  s$   e Zd Zdd Zdd Zdd ZdS )Serverc                 C  s   d S )N selfr	   r	   Z/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/networking.pyinstall_signal_handlers!   s    zServer.install_signal_handlersc                 C  sR   t j| jdd| _| j  t }| jsNtd t | dkr$tdq$d S )NT)targetdaemongMbP?   z@Server failed to start. Please check that the port is available.)		threadingThreadrunthreadstarttimestartedsleepr   )r   r   r	   r	   r   run_in_thread$   s    

zServer.run_in_threadc                 C  s   d| _ | j  d S )NT)Zshould_exitr   joinr
   r	   r	   r   close/   s    zServer.closeN)__name__
__module____qualname__r   r   r   r	   r	   r	   r   r       s   r   int)initialfinalreturnc              	   C  s|   t | |D ]R}z:t }|tjtjd |t|f |  |W   S  tyZ   Y q
0 q
td|  d|d  ddS )a-  
    Gets the first open port in a specified range of port numbers
    Parameters:
    initial: the initial value in the range of port numbers
    final: final (exclusive) value in the range of port numbers, should be greater than `initial`
    Returns:
    port: the first open port in the range
       zAll ports from z to z! are in use. Please close a port.N)	rangesocket
setsockopt
SOL_SOCKETSO_REUSEADDRbindLOCALHOST_NAMEr   OSError)r    r!   portsr	   r	   r   get_first_available_port4   s    	
r.   r   r   )appblocksr"   c                 C  sX   |j }|d ur0t|s(dd |D | _ q6|| _ nd | _ || _t | _|j| _i | _| S )Nc                 S  s   i | ]}|d  |d qS )r   r#   r	   ).0accountr	   r	   r   
<dictcomp>O       z!configure_app.<locals>.<dictcomp>)authcallabler0   osgetcwdcwdZfavicon_pathtokens)r/   r0   r5   r	   r	   r   configure_appK   s    
r;   z
str | Nonez
int | Nonezdict | Nonez!tuple[str, int, str, App, Server])r0   server_nameserver_portssl_keyfilessl_certfilessl_keyfile_password
app_kwargsr"   c                 C  sh  |dur|du rt d|pt}|dkr,dn|}|drR|drR|dd }n|}tj| |d	}	|durr|gntttt }
|
D ]}zht		 }|
t	jt	jd |t|f |  tj|	||d
|||dd}t|d}|  W  q*W q ttfy   Y q0 qtdt|
 dt|
 d|durHd| d| d}nd| d| d}||||	|fS )ar  Launches a local server running the provided Interface
    Parameters:
        blocks: The Blocks object to run on the server
        server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME.
        server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT.
        auth: If provided, username and password (or list of username-password tuples) required to access the Blocks. Can also provide function that takes username and password and returns True if valid login.
        ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
        ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
        ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
        app_kwargs: Additional keyword arguments to pass to the gradio.routes.App constructor.

    Returns:
        port: the port number the server is running on
        path_to_local_server: the complete address that the local server can be accessed at
        app: the FastAPI app object
        server: the server object that is a subclass of uvicorn.Server (used to close the server)
    Nz9ssl_certfile must be provided if ssl_keyfile is provided.z0.0.0.0	localhost[]r#   )rA   warningi   @)r/   r,   hostZ	log_levelr>   r?   r@   Zws_max_size)configz!Cannot find empty port in range: -z. You can specify a different port by setting the GRADIO_SERVER_PORT environment variable or passing the `server_port` parameter to `launch()`.zhttps://:/zhttp://)
ValueErrorr*   
startswithendswithr   Z
create_appr$   INITIAL_PORT_VALUETRY_NUM_PORTSr%   r&   r'   r(   r)   r   uvicornZConfigr   r   r+   r   minmax)r0   r<   r=   r>   r?   r@   rA   Zurl_host_namerG   r/   Zserver_portsr,   r-   rH   serverZpath_to_local_serverr	   r	   r   start_server[   sP    


rU   str)
local_host
local_portshare_tokenr"   c           
   
   C  s   t t}|r|jdkrz@| d }|d t|d  }}t||| ||}| }|W S  ty }	 zt	t
|	|	W Y d }	~	n
d }	~	0 0 t	dd S )N   r   rG   r,   z0Could not get share link from Gradio API Server.)requestsgetGRADIO_API_SERVERstatus_codejsonr   r   Zstart_tunnel	ExceptionRuntimeErrorrV   )
rW   rX   rY   responsepayloadremote_hostremote_portZtunneladdresser	   r	   r   setup_tunnel   s    

$rh   bool)urlr"   c              	   C  s   zpt dD ]b}t * td tj| ddd}W d    n1 sF0    Y  |jdv rb W dS td q
W n t	tj
j	fy   Y dS 0 dS )	Nr   ignore   F)timeoutverify)rZ   i  i.  Tg      ?)r$   warningscatch_warningsfilterwarningsr[   headr^   r   r   ConnectionError
exceptions)rj   _rr	   r	   r   url_ok   s    

.
rw   )NNNNNN) __doc__
__future__r   r7   r%   r   r   ro   typingr   r[   rQ   Zgradio.exceptionsr   Zgradio.routesr   Zgradio.tunnelingr   Zgradio.blocksr   r   getenvrO   rP   r*   r]   r   r.   r;   rU   rh   rw   r	   r	   r	   r   <module>   s<         Z