a
    d`                     @  sN  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m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 dd
lmZmZ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) ddl*m+Z+m,Z, ddl-m.Z. ddl/Z/ddl0m1Z1 ddl2m3Z3 erzddl4m5Z5m6Z6m7Z7 ddl8m9Z9 e	j:;e	j:<e/j=dZ>e
?e@dpdAdB ZCe.dZDe"dZEddddZFddddZGddddZHddd d!ZId"dd#d$ZJddd%d&ZKd'd'd(d)d*ZLd+d,d-d.d/ZMd,dd0d1ZNd2d3d4d5d6ZOdd8d8d9d:d;d<ZPd'd=d>d?d@ZQdd8dd8dBdCdDZRdEdFdGdHdIZSd'dJdKdLdMZTd2dNdOdPZUdQdR ZVG dSdT dTZWdUdV ZXG dWdX dXZYedYdZd[d\ZZd]d]d^d_d`Z[d3d3dadbdcZ\d'dddedfdgZ]d'ddhdidjZ^dkdl Z_d2dmd2dndodpZ`ddqdrZad2dsd"dtdudvZbdwdxdydzZcd'd{dd|d}d~ZddddddZedd Zfdd Zgd2dddddZhdddddZiG dd dejZkG dd dZldd ZmdddddZndddddZodd"dddZpeqdZrd"d'dddZsd{dddZtdS )z Handy utility functions.     )annotationsN)contextmanager)Enum)BytesIO)Number)Path)GeneratorType)TYPE_CHECKINGAnyCallable	GeneratorOptionalTypeVarUnion)Serializable)	BaseModelparse_obj_as)	ParamSpec)Context)en)BlockBlockContextBlocks)	Componentzlaunches.jsonzversion.txt    asciiPTboolreturnc               	   C  sF   d} z&ddl m} | }dt|v r(d} W n ttfy@   Y n0 | S )zf
    Check if interface is launching from Google Colab
    :return is_colab (bool): True or False
    Fr   get_ipythonzgoogle.colabT)IPython.core.getipythonr"   strImportError	NameError)Zis_colabr"   Z
from_ipynb r'   U/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/utils.pycolab_check<   s    r)   c                   C  s   t tjdptjdS )NZKAGGLE_KERNEL_RUN_TYPEZGFOOTBALL_DATA_DIR)r   osenvirongetr'   r'   r'   r(   kaggle_checkM   s    r-   c                  C  sF   z,dd l } | d}| }d|d  v W S  ty@   Y dS 0 d S )Nr   stsZ	sagemakerZArnF)boto3clientZget_caller_identitylower	Exception)r/   r0   responser'   r'   r(   sagemaker_checkS   s    
r4   c               	   C  s>   d} zddl m} | dur d} W n ttfy8   Y n0 | S )zo
    Check if interface is launching from iPython (not colab)
    :return is_ipython (bool): True or False
    Fr   r!   NT)r#   r"   r%   r&   )Z
is_ipythonr"   r'   r'   r(   ipython_check^   s    
r5   z
str | Nonec                   C  s   t ddkrt dS d S )NZSYSTEMspacesZSPACE_IDr*   getenvr'   r'   r'   r(   	get_spacen   s    
r9   c                   C  s   t ddkS )NZSPACES_ZERO_GPUtruer7   r'   r'   r'   r(   is_zero_gpu_spacet   s    r;   r$   )articler    c                 C  sB   z&t j| dd}|jt jjkr$|j} W n t jjy<   Y n0 | S )N   )timeout)requestsr,   status_codecodesoktext
exceptionsRequestException)r<   r3   r'   r'   r(   readme_to_htmlx   s    
rF   zgradio.BlocksNone)	interfacer    c                 C  s2   | j r.t dk r.ttd }td|  d S )Ng      ?ZTIPSzTip: )Z	show_tipsrandomchoicer   print)rH   Ztipr'   r'   r(   show_tip   s    rL   c                  C  s   zt jtsNddi} ttd}t| | W d    q1 sB0    Y  ntt}t|} W d    n1 sv0    Y  | d  d7  < | d dv rtt	d  ttd }|
t|  W d    n1 s0    Y  W n ty   Y n0 d S )Nlaunches   zw+)   2      i  i  ZBETA_INVITEw)r*   pathexists	JSON_PATHopenjsondumploadrK   r   writedumpsr2   )rM   jr'   r'   r(   launch_counter   s    ,
(2r]   r   z	list[Any])funcr    c                 C  s   t | }dd |j D S )Nc                 S  s$   g | ]}|j tjjur|j nd qS N)defaultinspect	Parameterempty.0vr'   r'   r(   
<listcomp>   s   z$get_default_args.<locals>.<listcomp>)ra   	signature
parametersvalues)r^   rh   r'   r'   r(   get_default_args   s    
rk   modedicttuple)config1config2	root_keysc                   sd  t t tjdd|D ]"}| | ks$J d| q$td td kshJ dfdd  fdd	d
 d }d
 d }|| td d D ]\}}t|d|dD ]\}}	 ||	 qt|d|dD ]\}
} |
| qt|d|dD ]\}} || q.||ksJ | d| qdS )a  Allows you to test if two different Blocks configs produce the same demo.

    Parameters:
    config1 (dict): nested dict with config from the first Blocks instance
    config2 (dict): nested dict with config from the second Blocks instance
    root_keys (Tuple): an interable consisting of which keys to test for equivalence at
        the root level of the config. By default, only "mode" is tested,
        so keys like "version" are ignored.
       )indentzConfigs have different: 
componentsz# of components are differentc                   s   t t fddd d }t tfddd d }t|}|d t|}|d t|t|ksJ | d| d S )Nc                   s   | d  kS Nidr'   c)
config1_idr'   r(   <lambda>   r   z[assert_configs_are_equivalent_besides_ids.<locals>.assert_same_components.<locals>.<lambda>ru   r   c                   s   | d  kS rv   r'   rx   )
config2_idr'   r(   r{      r   rw    does not match )listfiltercopydeepcopypoprW   r[   pprint)rz   r|   Zc1c2)rp   rq   pp)rz   r|   r(   assert_same_components   s    



zIassert_configs_are_equivalent_besides_ids.<locals>.assert_same_componentsc                   sL   t | |D ]<\}} |d |d  d|v s4d|v r
|d |d  q
d S )Nrw   children)zip)	children1Zchidren2Zchild1Zchild2)r   same_children_recursiver'   r(   r      s    zJassert_configs_are_equivalent_besides_ids.<locals>.same_children_recursiveZlayoutr   dependenciestargetsinputsoutputsr}   T)r   r   r   PrettyPrinterlenr   r   )rp   rq   rr   keyr   Z	children2d1Zd2t1t2i1i2Zo1Zo2r'   )r   rp   rq   r   r   r(   )assert_configs_are_equivalent_besides_ids   s0    

 
r   zlist[dict[str, str | int]])input_string
ner_groupsc                 C  s   t |dkr| d fgS g }d}d}|D ]P}|d |d |d   }}}|| || d f || || |f |}q&|| |d  d f |S )Nr   Zentity_groupstartend)r   append)r   r   outputr   Zprev_endgroupentityr   r'   r'   r(   format_ner_list   s    
r   F)_dict
skip_valuer    c                 C  s8   t |  D ]&\}}|r$|dkr$qq|du r| |= q| S )z=
    Delete keys whose values are None from a dictionary
    valueN)r~   items)r   r   r   r   r'   r'   r(   delete_none   s    r   zlist[Any] | Anyr
   )_listr    c                 C  s   t | dkr| d S | S d S )NrN   r   )r   )r   r'   r'   r(   resolve_singleton   s    r   z$type[Component] | type[BlockContext])cls_namer    c                 C  s   ddl }ddl}ddl}ddl}dd |jj D }dd |jj D }dd |jj D }|| | D ]@\}}|	 | 
ddkrnt||jjst||jjrn|  S qntd	|  dS )
z
    Returns the component, template, or layout class with the given class name, or
    raises a ValueError if not found.

    Parameters:
    cls_name (str): lower-case string class name of a component
    Returns:
    cls: the component class
    r   Nc                 S  s"   g | ]\}}t |tr||fqS r'   
isinstancetypere   nameclsr'   r'   r(   rg     s   
z-component_or_layout_class.<locals>.<listcomp>c                 S  s"   g | ]\}}t |tr||fqS r'   r   r   r'   r'   r(   rg     s   
c                 S  s"   g | ]\}}t |tr||fqS r'   r   r   r'   r'   r(   rg     s   
_ zNo such component or layout: )gradio.blocksgradio.componentsZgradio.layoutsZgradio.templatesru   __dict__r   	templateslayoutsr1   replace
issubclassr   blocksr   
ValueError)r   gradioru   r   r   r   r   r'   r'   r(   component_or_layout_class   s*    




r   )r^   c                 O  s   t  }|| |i |S )a?  
    Runs coroutines in background.

    Warning, be careful to not use this function in other than FastAPI scope, because the event_loop has not started yet.
    You can use it in any scope reached by FastAPI app.

    correct scope examples: endpoints in routes, Blocks.process_api
    incorrect scope examples: Blocks.launch

    Use startup_events in routes.py if you need to run a coro in background in Blocks.launch().


    Example:
        utils.run_coro_in_background(fn, *args, **kwargs)

    Args:
        func:
        *args:
        **kwargs:

    Returns:

    )asyncioZget_event_loopZcreate_task)r^   argskwargsZ
event_loopr'   r'   r(   run_coro_in_background'  s    r   c                 C  s*   z
t | W S  ty$   t dY n0 dS )z;Helper for yielding StopAsyncIteration from sync iterators.N)nextStopIterationStopAsyncIterationiteratorr'   r'   r(   run_sync_iterator_asyncC  s    
r   c                   @  s.   e Zd ZdZddddZdd Zdd	 Zd
S )SyncToAsyncIteratorz*Treat a synchronous iterator as async one.rG   r   c                 C  s   || _ || _d S r_   )r   limiter)selfr   r   r'   r'   r(   __init__O  s    zSyncToAsyncIterator.__init__c                 C  s   | S r_   r'   r   r'   r'   r(   	__aiter__S  s    zSyncToAsyncIterator.__aiter__c                   s   t jjt| j| jdI d H S )N)r   )anyioZ	to_threadZrun_syncr   r   r   r   r'   r'   r(   	__anext__V  s    
zSyncToAsyncIterator.__anext__N)__name__
__module____qualname____doc__r   r   r   r'   r'   r'   r(   r   L  s   r   c                   s   |   I d H S r_   )r   r   r'   r'   r(   async_iteration\  s    r   c                	   @  s   e Zd ZdZe ZG dd deeZ	dde
ddddddd	d
dddddZddddZd dddZeddddddZdd ZddddZdd  Zd0ddd!d"d#Zd$d% Zed&d' Zed(d) Zed*d+ Zed,d- Zed.d/ ZdS )1AsyncRequesta  
    The AsyncRequest class is a low-level API that allow you to create asynchronous HTTP requests without a context manager.
    Compared to making calls by using httpx directly, AsyncRequest offers several advantages:
        (1) Includes response validation functionality both using validation models and functions.
        (2) Exceptions are handled silently during the request call, which provides the ability to inspect each one
        request call individually in the case where there are multiple asynchronous request calls and some of them fail.
        (3) Provides HTTP request types with AsyncRequest.Method Enum class for ease of usage

    AsyncRequest also offers some util functions such as has_exception, is_valid and status to inspect get detailed
    information about executed request call.

    The basic usage of AsyncRequest is as follows: create a AsyncRequest object with inputs(method, url etc.). Then use it
    with the "await" statement, and then you can use util functions to do some post request checks depending on your use-case.
    Finally, call the get_validated_data function to get the response data.

    You can see example usages in test_utils.py.
    c                   @  s8   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdS )zAsyncRequest.Methodzf
        Method is an enumeration class that contains possible types of HTTP request methods.
        *CONNECTHEADGETDELETEOPTIONSPATCHPOSTPUTTRACEN)r   r   r   r   ANYr   r   r   r   r   r   r   r   r   r'   r'   r'   r(   Methodv  s   r   NF)validation_modelvalidation_functionexception_typeraise_for_statusr0   r$   ztype[BaseModel] | NonezUnion[Callable, None]ztype[Exception]r   zhttpx.AsyncClient | None)methodurlr   r   r   r   r0   c          	      K  sP   d| _ d| _|| _|| _|| _|| _d| _| j||fi || _|pH| j	| _
dS )aR  
        Initialize the Request instance.
        Args:
            method(Request.Method) : method of the request
            url(str): url of the request
            *
            validation_model(Type[BaseModel]): a pydantic validation class type to use in validation of the response
            validation_function(Callable): a callable instance to use in validation of the response
            exception_class(Type[Exception]): a exception type to throw with its type
            raise_for_status(bool): a flag that determines to raise httpx.Request.raise_for_status() exceptions.
        N)
_exception_status_raise_for_status_validation_model_validation_function_exception_type_validated_data_create_request_requestr0   client_)	r   r   r   r   r   r   r   r0   r   r'   r'   r(   r     s    zAsyncRequest.__init__z"Generator[None, Any, AsyncRequest]r   c                 C  s   |    S )zq
        Wrap Request's __await__ magic function to create request calls which are executed in one line.
        )_AsyncRequest__run	__await__r   r'   r'   r(   r     s    zAsyncRequest.__await__c              
     s   zN| j | jI dH | _| jj| _| jr2| j  | j | _	| 
| j	| _W n0 ty~ } z| || _W Y d}~n
d}~0 0 | S )a  
        Manage the request call lifecycle.
        Execute the request by sending it through the client, then check its status.
        Then parse the request into Json format. And then validate it using the provided validation methods.
        If a problem occurs in this sequential process,
        an exception will be raised within the corresponding method, and allowed to be examined.
        Manage the request call lifecycle.

        Returns:
            Request
        N)r   sendr   	_responser@   r   r   r   rW   _json_response_data_validate_response_datar   r2   r   r   )r   	exceptionr'   r'   r(   Z__run  s    


"zAsyncRequest.__runzhttpx.Request)r   r   r    c                 K  s   t j| |fi |}|S )z
        Create a request. This is a httpx request wrapper function.
        Args:
            method(Request.Method): request method type
            url(str): target url of the request
            **kwargs
        Returns:
            Request
        )httpxRequest)r   r   r   requestr'   r'   r(   r     s    zAsyncRequest._create_requestc              
   C  sX   |}z$| j r| |}| jr&| |}W n* tyR } z|| _W Y d}~n
d}~0 0 |S )aA  
        Validate response using given validation methods. If there is a validation method and response is not valid,
        validation functions will raise an exception for them.
        Args:
            response(ResponseJson): response object
        Returns:
            ResponseJson: Validated Json object.
        N)r   _validate_response_by_modelr   )_validate_response_by_validation_functionr2   r   )r   r3   Zvalidated_responser   r'   r'   r(   r     s    
z$AsyncRequest._validate_response_datar   c                 C  s   t  }| jrt| j|}|S )z
        Validate response json using the validation model.
        Args:
            response(ResponseJson): response object
        Returns:
            ResponseJson: Validated Json object.
        )r   r   r   r   r3   Zvalidated_datar'   r'   r(   r     s    z(AsyncRequest._validate_response_by_modelc                 C  s   d}| j r|  |}|S )z
        Validate response json using the validation function.
        Args:
            response(ResponseJson): response object
        Returns:
            ResponseJson: Validated Json object.
        N)r   r   r'   r'   r(   r     s    
z6AsyncRequest._validate_response_by_validation_function)raise_exceptionsr    c                 C  s"   | j r| jr|r| jdS dS dS )z
        Check response object's validity+. Raise exceptions if raise_exceptions flag is True.
        Args:
            raise_exceptions(bool) : a flag to raise exceptions in this check
        Returns:
            bool: validity of the data
        FTNhas_exceptionr   )r   r   r'   r'   r(   is_valid  s
    zAsyncRequest.is_validc                 C  s   | j S r_   )r   r   r'   r'   r(   get_validated_data#  s    zAsyncRequest.get_validated_datac                 C  s   | j S r_   )r   r   r'   r'   r(   rW   &  s    zAsyncRequest.jsonc                 C  s   | j S r_   )r   r   r'   r'   r(   r   *  s    zAsyncRequest.exceptionc                 C  s
   | j d uS r_   )r   r   r'   r'   r(   r   .  s    zAsyncRequest.has_exceptionc                 C  s   | j r| jr| jd S r_   r   r   r'   r'   r(   r   2  s    zAsyncRequest.raise_exceptionsc                 C  s   | j S r_   )r   r   r'   r'   r(   status7  s    zAsyncRequest.status)F)r   r   r   r   r   ZAsyncClientr0   r$   r   r   r2   r   r   r   staticmethodr   r   r   r   r   r  propertyrW   r   r   r   r  r'   r'   r'   r(   r   a  s8   "



r   z
Path | str)rS   c              	   c  s:   t   }zt|  dV  W t| nt| 0 dS )zBContext manager that sets the working directory to the given path.N)r   absoluter*   chdir)rS   originr'   r'   r(   set_directory<  s
    

r  zstr | Number)r   r    c                   sX   t  tr S g d}g d}t fdd|D sJt fdd|D rTd    S )z
    Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.
    Reference: https://owasp.org/www-community/attacks/CSV_Injection
    )=+-@	
)z,=z,+z,-z,@z,	z,
c                 3  s   | ]}  |V  qd S r_   )
startswith)re   prefixr   r'   r(   	<genexpr>P  r   z)sanitize_value_for_csv.<locals>.<genexpr>c                 3  s   | ]}| v V  qd S r_   r'   )re   sequencer  r'   r(   r  P  s   ')r   r   any)r   Zunsafe_prefixesZunsafe_sequencesr'   r  r(   sanitize_value_for_csvG  s    
"
r  )rj   r    c                 C  sH   g }| D ]:}t |tr0dd |D }|| qt|}|| q|S )z
    Sanitizes a list of values (or a list of list of values) that is being written to a
    CSV file to prevent CSV injection attacks.
    c                 S  s   g | ]}t |qS r'   )r  rd   r'   r'   r(   rg   _  r   z)sanitize_list_for_csv.<locals>.<listcomp>)r   r~   r   r  )rj   Zsanitized_valuesr   Zsanitized_valuer'   r'   r(   sanitize_list_for_csvW  s    
r  z	list[str])r   list_of_namesc                 C  sN   t |}| |vr| S d}|  d| }||v rF|d7 }|  d| }q&|S dS )zSAppends a numerical suffix to `name` so that it does not appear in `list_of_names`.rN   r   N)set)r   r  Zset_of_namesZsuffix_counternew_namer'   r'   r(   append_unique_suffixg  s    r  )possible_urlr    c                 C  s^   ddi}z<t j| |d}|jdks,|jdkr>t j| |djW S |jW S  tyX   Y dS 0 d S )Nz
User-Agentz-gradio (https://gradio.app/; team@gradio.app))headersi  i  F)r?   headr@   r,   rB   r2   )r  r  Zhead_requestr'   r'   r(   validate_urlu  s    r  c                 C  s   t | tod| ddv S )NupdateZ__type__r   )r   rn   r,   )valr'   r'   r(   	is_update  s    r"  float)fneveryr    c                   s    fdd}|S )Nc                  7  s4   |  }t |tr|E d H  n|V  t  q d S r_   )r   r   timesleep)r   r   r%  r$  r'   r(   continuous_fn  s
    
z(get_continuous_fn.<locals>.continuous_fnr'   )r$  r%  r)  r'   r(  r(   get_continuous_fn  s    	r*  c           	        s   d u rg n d u rg n  t rLt fdd}|S trxt fdd}|S t rt fdd}|S t fdd}|S d S )	Nc                   s@   r  | i |2 z3 d H W }|V  q6 r<   d S r_   r'   r   r   r3   
after_argsafter_fnbefore_args	before_fnfr'   r(   asyncgen_wrapper  s    
z*function_wrapper.<locals>.asyncgen_wrapperc                    s0   r  | i |I d H }r,   |S r_   r'   r+  r,  r'   r(   async_wrapper  s    z'function_wrapper.<locals>.async_wrapperc                  ?  s0   r  | i |E d H  r,   d S r_   r'   )r   r   r,  r'   r(   gen_wrapper  s
    z%function_wrapper.<locals>.gen_wrapperc                    s*   r  | i |}r&   |S r_   r'   r+  r,  r'   r(   wrapper  s    z!function_wrapper.<locals>.wrapper)ra   isasyncgenfunction	functoolswrapsr   iscoroutinefunctionisgeneratorfunction)	r1  r0  r/  r.  r-  r2  r3  r4  r5  r'   r,  r(   function_wrapper  s"    


r;  r   )r$  r   event_idc                 C  s   dd }t | |||fdS )Nc                 S  s   ddl m} | |_||_d S )Nr   )thread_data)gradio.contextr=  r   r<  )r   r<  r=  r'   r'   r(   r0    s    z+get_function_with_locals.<locals>.before_fn)r0  r/  )r;  )r$  r   r<  r0  r'   r'   r(   get_function_with_locals  s    r?  zset[str]task_idsc                   sB    fddt  D }|D ]}|  qt j|ddiI d H  d S )Nc                   s   g | ]}|   v r|qS r'   )get_name)re   taskr@  r'   r(   rg     s   z cancel_tasks.<locals>.<listcomp>Zreturn_exceptionsT)r   Z	all_taskscancelZgather)rA  Zmatching_tasksrC  r'   r@  r(   cancel_tasks  s    

rE  int)session_hashfn_indexbatchc                 C  s   |s|  | d|  d S )Nr   )set_name)rC  rG  rH  rI  r'   r'   r(   set_task_name  s    rK  zlist[dict[str, Any]]ztuple[Callable, list[int]])r   r    c                   sl   i | D ]> t jrt fddtt jjD }dd  d D |< qdddfd	d
}|t fS )Nc                 3  s   | ]\}}| kr|V  qd S r_   r'   )re   id)depr'   r(   r    s   z&get_cancel_function.<locals>.<genexpr>c                 S  s   g | ]}t jj| qS r'   )r   
root_blockr   )re   or'   r'   r(   rg     s   z'get_cancel_function.<locals>.<listcomp>r   r$   rG   )rG  r    c                   s$    fddD }t |I d H  d S )Nc                   s   h | ]}  d | qS )r   r'   )re   r$  rG  r'   r(   	<setcomp>  r   z6get_cancel_function.<locals>.cancel.<locals>.<setcomp>)rE  )rG  rA  )
fn_to_comprQ  r(   rD    s    z#get_cancel_function.<locals>.cancel)r   rO  r   	enumerater   r~   keys)r   rH  rD  r'   )rN  rS  r(   get_cancel_function  s    

rV  c                 C  s   dd l }ddl m}m} t| sBt| r.nt| r>| j} ni S zt	| W S  t
y   i }t| }|j D ]x\}}|jtjju rqt|jdkrt| ||< dt|jv rqtz"tt|jt t ||< W qt tt
fy   Y qt0 qt| Y S 0 d S )Nr   )OAuthProfiler   zgr.OAuthProfile | None|)r   rW  r   ra   
isfunctionismethodcallable__call__typingget_type_hints	TypeErrorrh   ri   r   
annotationrb   rc   r   r$   
_eval_type
ForwardRefglobalslocalsr&   )r$  ZgrrW  r   Z
type_hintssigr   paramr'   r'   r(   r^    s4    

r^  c           	      C  sn   ddl m} ddlm} ddlm} || }|s6dS ||k}||t| fv }t	|o`t
||}|pl|pl|S )Nr   )	EventData)rW  )r   F)Zgradio.helpersrg  Zgradio.oauthrW  Zgradio.routesr   r,   r   ra   isclassr   )	r   parameter_typesrg  rW  r   hintZ
is_requestZis_oauth_argZis_event_datar'   r'   r(   is_special_typed_parameter#  s    
rk  r~   )r$  r   inputs_as_dictc              	   C  s<  t | }t| }d}d}d}|j D ]v\}}	|	j|	jk}
|	j|	j|	j	fv rnt
||s|
sd|d7 }|d7 }q(|	j|	jkr|}q(|	j|	jkr(|
s(d|    S q(|rdnt|}||kr||krtd| d|  d| d ||k rtd	| d|  d| d ||kr8||kr8td
| d|  d| d dS )z
    Checks if the input component set matches the function
    Returns: None if valid, a string error message if mismatch
    r   rN   z8Keyword-only args must have default values for function z	Expected z arguments for function z, received .zExpected at least zExpected maximum N)ra   rh   r^  ri   r   r`   rc   kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDrk  VAR_POSITIONALKEYWORD_ONLYr   warningswarn)r$  r   rl  rh   ri  Zmin_argsZmax_argsZinfinityr   rf  Zhas_default	arg_countr'   r'   r(   check_function_inputs_match2  s:    



rw  zCallable[P, T])queuer    c                   s$   t  dddd fdd}|S )NzP.argszP.kwargsr   )r   r   r    c                    s:   | ^}}t  r,t|dks"d|v r,td  | i |S )NrN   Zconcurrency_countzQueue concurrency_count on ZeroGPU Spaces cannot be overriden and is always equal to Block's max_threads. Consider setting max_threads value on the Block instead)r;   r   rt  ru  )r   r   _self
positionalrx  r'   r(   r5  X  s    
z*concurrency_count_warning.<locals>.wrapper)r7  r8  )rx  r5  r'   r{  r(   concurrency_count_warningW  s    r|  c                   @  s   e Zd Zdd Zdd ZdS )TupleNoPrintc                 C  s   dS Nr   r'   r   r'   r'   r(   __repr__j  s    zTupleNoPrint.__repr__c                 C  s   dS r~  r'   r   r'   r'   r(   __str__m  s    zTupleNoPrint.__str__N)r   r   r   r  r  r'   r'   r'   r(   r}  h  s   r}  c                   @  s   e Zd Zdd Zdd ZdS )MatplotlibBackendManangerc                 C  s   t  | _t d d S )NZagg)
matplotlibget_backend_original_backenduser   r'   r'   r(   	__enter__r  s    
z#MatplotlibBackendMananger.__enter__c                 C  s   t | j d S r_   )r  r  r  )r   exc_typeexc_valexc_tbr'   r'   r(   __exit__v  s    z"MatplotlibBackendMananger.__exit__N)r   r   r   r  r  r'   r'   r'   r(   r  q  s   r  c              	   G  s>  t   dd lm} d}d}|jddd |jdd}|jddd	|  d	|d
 t }|j||ddddd || |	d |
 d}|d}||d  }	tjdd|	tjd}	tdd|	}	td|	}
|
rt|
d}|| }tdd| d|	}	d|  d}W d    n1 s(0    Y  | |	 S )Nr      i,  Zmathtextcm)Zfontset){Gz?r  )Zfigsize$)fontsizeTsvgZtightg        )dpiZtransparentformatZbbox_inchesZ
pad_incheszutf-8z<svg z<metadata>.*<\/metadata>r   )flagsz width="[^"]+"zheight="([\d.]+)pt"rN   zheight="[\d.]+pt"zheight="zem"z<span style='font-size: 0px'>z</span>)r  Zmatplotlib.pyplotZpyplotrcfigurerC   r   ZsavefigcloseseekreaddecodeindexresubDOTALLsearchr#  r   )Zformular   Zpltr  r  Zfigr   Zxml_codeZ	svg_startZsvg_codeZheight_matchheightZ
new_heightZ	copy_coder'   r'   r(   tex2svgz  s@    



,r  z
str | Pathr   )rS   r    c                 C  sX   t | } |  r| S |  p.tdd | jD }|s@| |  krLt  |  S |  S dS )zKReturns absolute path of a str or Path path, but does not resolve symlinks.c                 s  s   | ]}|  V  qd S r_   )
is_symlink)re   parentr'   r'   r(   r    s   zabspath.<locals>.<genexpr>N)r   is_absoluter  r  parentsresolvecwd)rS   r  r'   r'   r(   abspath  s    r  Zpath_1Zpath_2c                 C  sJ   t | t | } }zt| |dr.W dS W n tyD   Y dS 0 dS )z
    True if path_1 is a descendant (i.e. located within) path_2 or if the paths are the
    same, returns False otherwise.
    Parameters:
        path_1: str or Path (should be a file)
        path_2: str or Path (can be a file or directory)
    z..FT)r  r$   relative_tor  r   r  r'   r'   r(   is_in_or_equal  s    
r  r   )blockr    c                   s8   t | dsd S dd fdd  | j}|r4|jS d S )N	serializer   )methc                   s   t | tjr | jS t| sHt| rt| dd d urt| jdd rt	| jj
D ]4}t|trvd|jv rv|  S | j|jv rV|  S qVt| d| } t| rtt| | jddd ddd d }t |tr|S t| d	d S )
N__self__	__class__Zgradio_client__func__z	.<locals>rN   r   rn  __objclass__)r   r7  partialr^   ra   rZ  	isbuiltingetattrr  getmror  r   r   r   r   r   rY  	getmoduler   splitrsplitr   )r  r   get_class_that_defined_methodr'   r(   r    s0    




z:get_serializer_name.<locals>.get_class_that_defined_method)hasattrr  r   )r  r   r'   r  r(   get_serializer_name  s    

r  z<.*?>)raw_htmlr    c                 C  s   t td| pdS r~  )r  r  HTML_TAG_RE)r  r'   r'   r(   remove_html_tags  s    r  c                  C  sB   t  } d}| r>t | }d|tjdvr.q>| j} |d7 }q|S )z7
    Find the first stack frame not inside Gradio.
    r   z/gradio//rN   )ra   currentframegetfiler   r*   sepf_back)framenfnamer'   r'   r(   find_user_stack_level  s    

r  )rl   )F)NNNN)ur   
__future__r   r   r   r7  ra   rW   Zjson.decoderr*   pkgutilr   rI   r  r&  r]  rt  
contextlibr   enumr   ior   Znumbersr   pathlibr   typesr   r	   r
   r   r   r   r   r   r   r   r  r?   Zgradio_client.serializingr   Zpydanticr   r   Ztyping_extensionsr   r   r>  r   Zgradio.stringsr   r   r   r   r   r   r   rS   joindirname__file__rU   get_datar   r  stripZGRADIO_VERSIONr   r   r)   r-   r4   r5   r9   r;   rF   rL   r]   rk   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r"  r*  r;  r?  rE  rK  rV  r^  rk  rw  r|  ro   r}  r  r  r  r  r  compiler  r  r  r'   r'   r'   r(   <module>   s   $

	 9'	 \
 
9
	)%		$#
