
    l0j&'                    h   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
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 dd	lmZ dd
lmZmZ erddlmZ  e ej        dd                    Z e ej        dd                    Z ej        dd          ZdZ  e! ej        dd                    Z"e"r$ ej        dd          #                    d          ng Z$ ej        dd          Z% ej        dd          Z& G d dej'                  Z'd9d!Z(d:d%Z)	 	 	 	 	 	 d;d<d0Z*d=d5Z+d>d8Z,dS )?z^
Defines helper methods useful for setting up ports, launching servers, and
creating tunnels.
    )annotationsN)partial)TYPE_CHECKING)Config)ServerFailedToStartError)App)Tunnel)SourceFileReloaderwatchfn)BlocksGRADIO_SERVER_PORT7860GRADIO_NUM_PORTS100GRADIO_SERVER_NAMEz	127.0.0.1z(https://api.gradio.app/v2/tunnel-requestGRADIO_WATCH_DIRSF ,GRADIO_WATCH_FILEappGRADIO_WATCH_DEMO_NAMEdemoc                  6     e Zd Z	 dd fdZd	 Zd
 Zd Z xZS )ServerNconfigr   reloaderSourceFileReloader | NonereturnNonec                    |j         | _        t                                          |           || _        | j        r9t          j                    | _        t          t          | j                  | _
        d S d S N)r   running_appsuper__init__r   	threadingEventeventr   r   watch)selfr   r   	__class__s      T/home/wildlama/miniconda3/envs/lam/lib/python3.11/site-packages/gradio/networking.pyr$   zServer.__init__+   sh     ":    = 	9"**DJ $-88DJJJ	9 	9    c                    d S r!    r)   s    r+   install_signal_handlerszServer.install_signal_handlers5   s    r,   c                   t          j        | j        d          | _        | j        r9t          j        | j        d          | _        | j                                         | j                                         t          j                    }| j	        sFt          j
        d           t          j                    |z
  dk    rt          d          | j	        Dd S d S )NT)targetdaemongMbP?   z@Server failed to start. Please check that the port is available.)r%   Threadrunthreadr   r(   watch_threadstarttimestartedsleepr   )r)   r9   s     r+   run_in_threadzServer.run_in_thread8   s    &dhtDDD= 	& ) 0
4 P P PD##%%%	, 	Jty{{U"Q&&.V   , 	 	 	 	 	r,   c                    d| _         | j        r2| j                                         | j                                         | j                                         d S )NT)should_exitr   stopr8   joinr7   r/   s    r+   closezServer.closeF   sW    = 	%M   ""$$$r,   r!   )r   r   r   r   r   r   )__name__
__module____qualname__r$   r0   r=   rB   __classcell__)r*   s   @r+   r   r   *   sr        DH9 9 9 9 9 9 9          r,   r   initialintfinalr   c                ^   t          | |          D ]}	 t          j                    }|                    t          j        t          j        d           |                    t          |f           |                                 |c S # t          $ r Y w xY wt          d|  d|dz
   d          )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.)	rangesocket
setsockopt
SOL_SOCKETSO_REUSEADDRbindLOCALHOST_NAMErB   OSError)rG   rI   portss       r+   get_first_available_portrV   N   s     gu%%  	ALL*F,?CCCFFND)***GGIIIKKK 	 	 	D	
S'SSuqySSS  s   A/B
BBr   blocksr   c                    |j         }|)t          |          sd |D             | _         n|| _         nd | _         || _        t          j                    | _        |j        | _        i | _        | S )Nc                ,    i | ]}|d          |d         S )r   rK   r.   ).0accounts     r+   
<dictcomp>z!configure_app.<locals>.<dictcomp>i   s"    CCC7
GAJCCCr,   )authcallablerW   osgetcwdcwdfavicon_pathtokens)r   rW   r]   s      r+   configure_apprd   e   so    ;D~~ 	CCdCCCCHHCHHCJikkCG*CCJJr,   server_name
str | Noneserver_port
int | Nonessl_keyfilessl_certfilessl_keyfile_password
app_kwargsdict | None!tuple[str, int, str, App, Server]c                   ||t          d          |pt          }|dk    rdn|}|                    d          r |                    d          r|dd         }n|}t	          j        | |	          }	||gn!t          t          t          t          z             }
|
D ]#}	 t          j	                    }|
                    t          j        t          j        d           |                    t          |f           |                                 t          j        |	||d
|||d          }d}t"          rOt%          j                    }||	_        t+          |	t"          t,          t.          t%          j                    |          }t1          ||          }|                                  nH# t4          t6          f$ r Y !w xY wt5          dt9          |
           dt;          |
           d          |
d| 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[]rK   )rl   warningi   @)r   rT   host	log_levelri   rj   rk   ws_max_size)r   
watch_dirs
watch_file	demo_name
stop_eventchange_event)r   r   z!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://)
ValueErrorrR   
startswithendswithr   
create_apprL   INITIAL_PORT_VALUETRY_NUM_PORTSrM   rN   rO   rP   rQ   rB   uvicornr   r   r%   r&   r|   r
   r   r   r   r=   rS   r   minmax)rW   re   rg   ri   rj   rk   rl   url_host_nameru   r   server_portsrT   rU   r   r   r|   serverpath_to_local_servers                     r+   start_serverr   u   s   4 <#7TUUU/K#.)#;#;KKM
 c"" {';';C'@'@ 1R4 
.J
7
7
7C " 
%'9M'IJJ   ,
 ,
'	 ALL*F,?CCC FFND)***GGIII ^#')%9.	 	 	F H  
(00#/ -004(00!-   6H===F  """E12 	 	 	D	  gL0A0A  g  gCDUDU  g  g  g
 
 	
 A-AA$AAA@@@@@@2C??s   !DF**F?>F?
local_hoststr
local_portshare_tokenc                   t          j        t                    }|r|j        dk    r	 |                                d         }|d         t          |d                   }}t          ||| ||          }|                                }|S # t          $ r"}	t          t          |	                    |	d }	~	ww xY wt          d          )N   r   ru   rT   z0Could not get share link from Gradio API Server.)requestsgetGRADIO_API_SERVERstatus_codejsonrH   r	   start_tunnel	ExceptionRuntimeErrorr   )
r   r   r   responsepayloadremote_hostremote_porttunneladdresses
             r+   setup_tunnelr      s    |-..H 
.H(C//		.mmooa(G'.vGFO8L8LK[*j+ F ))++GN 	. 	. 	.s1vv&&A-	.
I
J
JJs   AB 
B4B//B4urlboolc                ^   	 t          d          D ]x}t          j                    5  t          j        d           t	          j        | dd          }d d d            n# 1 swxY w Y   |j        dv r dS t          j        d           yn"# t          t          j
        j	        f$ r Y dS w xY wdS )	Nr4   ignore   F)timeoutverify)r   i  i.  Tg      ?)rL   warningscatch_warningsfilterwarningsr   headr   r:   r<   ConnectionError
exceptions)r   _rs      r+   url_okr      s   	q 	 	A(** @ @'111M#q???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ }//ttJu	 X0@A   uu5s:   $B ,AB A"	"B %A"	&B 5B B*)B*)rG   rH   rI   rH   r   rH   )r   r   rW   r   r   r   )NNNNNN)rW   r   re   rf   rg   rh   ri   rf   rj   rf   rk   rf   rl   rm   r   rn   )r   r   r   rH   r   r   r   r   )r   r   r   r   )-__doc__
__future__r   r_   rM   r%   r:   r   	functoolsr   typingr   r   r   uvicorn.configr   gradio.exceptionsr   gradio.routesr   gradio.tunnelingr	   gradio.utilsr
   r   gradio.blocksr   rH   getenvr   r   rR   r   r   should_watchsplitr   r   r   r   rV   rd   r   r   r   r.   r,   r+   <module>r      s    # " " " " " 				                            ! ! ! ! ! ! 6 6 6 6 6 6       # # # # # # 4 4 4 4 4 4 4 4 %$$$$$$ S#7@@AA IBI0%8899/==> tIBI1599::5AIIBI!2&&,,S111r  BI1599 "#;VDD ! ! ! ! !W^ ! ! !H   .   $ #""#'+"c@ c@ c@ c@ c@LK K K K      r,   