
    ;3hb                      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 ddlmZm Z  ddl!Z!ddl"Z"ddl"m#Z#m$Z$m%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/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> ej~                  j                  d      xs   eA e ej                               dz        ZC e3ddddd       G d d             ZDe G d d             ZEe G d  d!             ZF G d" d#      ZG e3d$d%d&       G d' d(e             ZHy))z,The main Client class for the Python client.    )annotationsN)Callable)Future)	dataclass)datetime)partial)Path)Lock)AnyLiteral)CommitOperationAddSpaceHardware
SpaceStage)RepositoryNotFoundErrorbuild_hf_headerssend_telemetry)version)utils)EndpointV3Compatibility)ParameterInfo)document)AppErrorAuthenticationError)Communicator	JobStatusMessage
QueueErrorServerMessageStatusStatusUpdateGRADIO_TEMP_DIRgradiopredictsubmitview_api	duplicatedeploy_discordc                     e Zd ZdZ	 	 	 	 	 ddedddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d dZd Zd Z	 	 	 	 d!dZd	 Z	e
	 	 	 	 	 	 	 	 d"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#d
       Zd Zddd	 	 	 	 	 d$dZd%dZdddd	 	 	 	 	 	 	 d&dZd Z	 	 	 d'	 	 	 	 	 	 	 d(dZd)dZd*dZ	 	 	 	 	 	 d+dZd Zd Zd)dZd,dZd Zd-dZd.dZd/dZ	 	 	 	 	 d0	 	 	 	 	 	 	 	 	 d1dZy)2Clienta  
    The main Client class for the Python client. This class is used to connect to a remote Gradio app and call its API endpoints.

    Example:
        from gradio_client import Client

        client = Client("abidlabs/whisper-large-v2")  # connecting to a Hugging Face Space
        client.predict("test.mp4", api_name="/predict")
        >> What a nice recording! # returns the result of the remote API call

        client = Client("https://bec81a83-5b5c-471e.gradio.live")  # connecting to a temporary Gradio share URL
        job = client.submit("hello", api_name="/predict")  # runs the prediction in a background thread
        job.result()
        >> 49 # returns the result of the remote API call (blocking call)
    TN)headersdownload_files
ssl_verify_skip_componentsanalytics_enabledc                  || _         || _        || _        |
| _        t	        |dt
        j                        | _        |r| j                  j                  |       |	| _	        d| _
        i | _        t        | j                  t        t        f      rt        j                   j#                  | j                        s!t        j$                  | j                  d       t        j                   j'                  | j                        st)        d| j                   d      t        | j                        | _        nt,        | _        |j/                  d      s|j/                  d	      r|j1                  d
      r|n|d
z   }n)| j3                  |      }|t)        d| d      || _
        || _        | j7                         }|t8        j:                  k(  rp| j                   rt=        d       | j7                         t8        j:                  k(  r8t?        j@                  d       	 | j7                         t8        j:                  k(  r8|t
        jB                  v rt)        d| d      | j                   rt=        d| j4                   d       |i n|| _"        || jG                  |       | jI                         | _%        | jJ                  jM                  dd      | _'        | jJ                  jM                  dd      }|jQ                  d
      d
z   | _)        tT        jV                  jY                  | j4                  | jR                        j[                  d
      d
z   | _.        tT        jV                  jY                  | j\                  t
        j^                        | _0        tT        jV                  jY                  | j\                  | jN                  dk(  rt
        jb                  nt
        jd                        | _3        tT        jV                  jY                  | j\                  t
        jh                        | _5        tT        jV                  jY                  | j\                  | jN                  dk(  rt
        jl                  nt
        jn                        | _8        tT        jV                  jY                  | j\                  js                  ddd      t
        jt                        | _;        tT        jV                  jY                  | j\                  t
        jx                        | _=        tT        jV                  jY                  | j\                  t
        j|                        | _?        t        jV                  | jJ                  jM                  dd            | _A        | j                         | _C        t        t        j                               | _F        | jN                  j/                  d      rt        nt        }t        | jJ                  d         D ci c];  \  }}|jM                  d|       || |jM                  d|      || jN                        = c}}| _J        t        j                  j                  |      | _N        |xs t        j                  dd       d k(  | _P        | j                  r/t        j                  | j                  d!      j                          t        j                         | _V        t        j                         | _W        t        j                  | j                  d!      | _Y        | j                  j                          d"| _Z        d| _[        i | _\        t               | _^        yc c}}w )#a  
        Parameters:
            src: either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-large-v2") or the full URL (including "http" or "https") of the hosted Gradio app to load (e.g. "http://mydomain.com/app" or "https://bec81a83-5b5c-471e.gradio.live/").
            hf_token: optional Hugging Face token to use to access private Spaces. By default, no token is sent to the server. Set `hf_token=None` to use the locally saved token if there is one (warning: only provide a token if you are loading a trusted private Space as the token can be read by the Space you are loading). Find your tokens here: https://huggingface.co/settings/tokens.
            max_workers: maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously.
            verbose: whether the client should print statements to the console.
            headers: additional headers to send to the remote Gradio app on every request. By default only the HF authorization and user-agent headers are sent. This parameter will override the default headers if they have the same keys.
            download_files: directory where the client should download output files  on the local machine from the remote API. By default, uses the value of the GRADIO_TEMP_DIR environment variable which, if not set by the user, is a temporary directory on your machine. If False, the client does not download files and returns a FileData dataclass object with the filepath on the remote machine instead.
            ssl_verify: if False, skips certificate validation which allows the client to connect to Gradio apps that are using self-signed certificates.
            httpx_kwargs: additional keyword arguments to pass to `httpx.Client`, `httpx.stream`, `httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http auth, etc.
            analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
        gradio_client)tokenlibrary_namelibrary_versionNTexist_okzPath: z is not a directory.zhttp://zhttps:///Could not find Space: z7. If it is a private Space, please provide an hf_token.z'Space is still building. Please wait...   z+The current space is in the invalid state: z'. Please contact the owner to fix this.zLoaded as API: u    ✔protocolws
api_prefix ssehttp   r   z2.0dependenciesid)max_workersGRADIO_ANALYTICS_ENABLEDTrue)targetdaemonF)_verbosehf_tokenr+   r-   r   r   __version__r*   updater,   space_idcookies
isinstancestrr	   ospathexistsmakedirsisdir
ValueError
output_dirDEFAULT_TEMP_DIR
startswithendswith_space_name_to_srcsrc_get_space_stater   BUILDINGprinttimesleepINVALID_RUNTIMEhttpx_kwargs_login_get_configconfiggetr9   lstripr;   urllibparseurljoinrstripsrc_prefixedAPI_URLapi_url
SSE_URL_V0SSE_URLsse_urlHEARTBEAT_URLheartbeat_urlSSE_DATA_URL_V0SSE_DATA_URLsse_data_urlreplaceWS_URLws_url
UPLOAD_URL
upload_url	RESET_URL	reset_urlr   app_version_get_api_info_infouuiduuid4session_hashEndpointr   	enumerate	endpoints
concurrentfuturesThreadPoolExecutorexecutorgetenvr.   	threadingThread_telemetry_threadstartEvent_refresh_heartbeat_kill_heartbeat_stream_heartbeat	heartbeatstream_openstreaming_futurepending_messages_per_eventsetpending_event_ids)selfrZ   rH   rB   rG   authra   r*   r+   r,   r-   r.   _srcstater;   endpoint_classfn_index
dependencys                     T/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio_client/client.py__init__zClient.__init__L   s   6  , 0'(!--

 LL($')d))C;777>>$"5"56D//$?77==!4!45 6$*=*=)>>R!STT!$"5"56DO.DO>>)$z(B,,s+3sD**3/D| ,SE1hi   DM%%'J'''||?@'')Z-@-@@

1 '')Z-@-@@ E)))=eW E8 8  <<ODHH:T23"."6BLKK&&(KKOOJ- 	 ++//,;
$++C036LL  4??;BB3G#M 	 ||++D,=,=u}}M||++ $ 6EEMM
 $\\11u22
 #LL00%)]]e%;E!!ASAS
 ll**%%fdA6
 !,,..t/@/@%BRBRS--d.?.?Q"==E)JK'')


- 007H=T 	 )2$++n2M(N	
 %* NN4*NjnnT84j$--- 
 #**==+=V X+Ev!NRX!X 	 !!D$:$:4HNNP"+//"3(0"))1G1GPTU /3KM'+.51
s   A ]#c                p    | j                   j                          | j                  j                  d       y )Nr?   timeout)r   r   r   joinr   s    r   closezClient.close   s)      "A&    c                Z   	 | j                   j                  | j                        }	 | j                  j	                         }|j                  dd       t        j                  d|f| j                  | j                  | j                  d|5 }|j                         D ]\  }| j                  j                         r| j                  j                           n&| j                  j                         sT d d d        y  d d d        # 1 sw Y   xY w# t        j                   $ r Y y w xY w)N)r   r      GETr*   rL   verify)rr   formatr   ra   copy
setdefaulthttpxstreamr*   rL   r,   
iter_linesr   is_setclearr   TransportError)r   urlra   response_s        r   r   zClient._stream_heartbeat   s   $$++9J9J+KC#00557''	26\\ !LL LL?? # # %002 #2299; 3399;!//668"# ### 
# # '' s=   A%D A$D3D4D =D>D DD D*)D*c                   	 | j                   j                         }|j                  dt        j                  d              t        j
                  dd| j                  i|5 }|j                  d| j                  d| j                  i| j                  | j                        5 }d}|j                         D ]  }||z  }d|v s|j                  dd	      \  }}|j                  d
      j                  d      }t!        |      sF|j#                  d      rjt%        j&                  |dd        }|d   t(        j*                  k(  r|j-                  dd      t(        j.                  k(  rB| j0                  j3                         D ]  }	|	j5                  |         d d d        d d d        y |d   t(        j6                  k(  rd| _         d d d        d d d        y |d   }
|
| j0                  vrg | j0                  |
<   | j0                  |
   j5                  |       |d   t(        j:                  k(  r| j<                  j?                  |
       t!        | j<                        dk(  r-|dk7  r(d| _         d d d        d d d        y tA        d| d      d|v rҐ 	 d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY w# tB        $ r:}tE        |t        jF                        rY d }~y dd l$}|jK                          |d }~ww xY w)Nr   r   r   r   r   )paramsr*   rL   r   s   

r?   utf-8
zdata:   msgmessager<   Fevent_idr   sse_v3zUnexpected SSE line: '' )&ra   r   r   r   Timeoutr)   r,   r   rp   r   r*   rL   
iter_bytessplitdecoderj   lenrW   jsonloadsr   r   re   server_stoppedr   valuesappendclose_streamr   process_completedr   removerT   BaseExceptionrM   RemoteProtocolError	traceback	print_exc)r   r9   ra   clientr   bufferchunklineresppending_messagesr   er   s                r   stream_messageszClient.stream_messages   s   =	,,113L##Iu}}T/JK  0S ]]LL*D,=,=> LL LL #  ,S  F!)!4!4!6 $S%%/+1<<+CLD&#';;w#7#>#>t#DD#&t9 (#w7'+zz$qr(';#';-2I2I#I$,$(HHY$;'4'C'C%D
 *.)H)H)O)O)Q%F(8(8(?(?(E%F %+7,S	0S 0S@ &*%[M4N4N%N7<D$4$*=,S	0S 0SF ,0
+;#+43R3R#RPRD$C$CH$M $ ? ? I P PQU V#';-2Q2Q#Q$($:$:$A$A($K$'(>(>$?1$D(0H(<7<D$4$*U,S	0S 0S` '13I$q1Q&R RE &/$S,S	0S 0S,S ,S	0S 0Sb  		 !U667!G		s   A!K #AJ8$ J,CJ,J8#K ,J,
J8K BJ,1J89K J,J,J8#K ,J5	1J88K=K K 	LL,LLc                J     j                   j                        }t        j                   j                  fi ||| j
                   j                  d j                  }|j                  dk(  rt        d      |j                          |j                         }|d   } j                  ssd _         fd} fd}	 j                   j                  j                         r; j                  j!                  |       _         j                  j#                  |	       |S )Nr   r*   rL   r   i  z Queue is full! Please try again.r   Tc                 &    j                         S N)r   )r9   r   s   r   open_streamz%Client.send_data.<locals>.open_streamF  s    ++H55r   c                z    d_         j                  j                         D ]  \  } }|j                  d         y )NF)r   r   itemsr   )r   r   r   s     r   r   z&Client.send_data.<locals>.close_streamI  s=    #( +/+J+J+P+P+R 2'A'$++D12r   )add_zero_gpu_headersr*   r   postru   rL   r,   ra   status_coder   raise_for_statusr   r   r   doner   r$   add_done_callback)
r   data	hash_datar9   r*   reqr   r   r   r   s
   `  `      r   	send_datazClient.send_data3  s   ++DLL9jj
&D&I&LL??
 
 ??c!?@@xxz
##D62
 $$,0E0E0J0J0L(,(<(<[(I%%%77Er   c
                   	 t        j                  ||      }
|r0d|v r|j	                  d      d   }t        j
                  ||      }n)t        j
                  |j	                  d      d   |      }	 t        j                  ||       |	r,t        dt        j                  j                  |       d       |t        j                  d	       t        j                  ||      }|j                  xs t         j                   j"                  }|xs |
j                  }||k7  r't        j$                  |||       t        d| d       |t         j                   j"                  k7  rt        j&                  |||dz         |	rt        d        | ||||	      }|S # t        $ r}t        d| d      |d}~ww xY w# t        $ r |	rt        d
| d       t        j                  |||d|       |2 |j                         D ]  \  }}t        j                  ||||         |	r+t        dt        j                  j                  |              Y w xY w)ak
  
        Duplicates a Hugging Face Space under your account and returns a Client object
        for the new Space. No duplication is created if the Space already exists in your
        account (to override this, provide a new name for the new Space using `to_id`).
        To use this method, you must provide an `hf_token` or be logged in via the Hugging
        Face Hub CLI.

        The new Space will be private by default and use the same hardware as the original
        Space. This can be changed by using the `private` and `hardware` parameters. For
        hardware upgrades (beyond the basic CPU tier), you may be required to provide
        billing information on Hugging Face: https://huggingface.co/settings/billing

        Parameters:
            from_id: The name of the Hugging Face Space to duplicate in the format "{username}/{space_id}", e.g. "gradio/whisper".
            to_id: The name of the new Hugging Face Space to create, e.g. "abidlabs/whisper-duplicate". If not provided, the new Space will be named "{your_HF_username}/{space_id}".
            hf_token: optional Hugging Face token to use to duplicating private Spaces. By default, no token is sent to the server. Set `hf_token=None` to use the locally saved token if there is one. Find your tokens here: https://huggingface.co/settings/tokens.
            private: Whether the new Space should be private (True) or public (False). Defaults to True.
            hardware: The hardware tier to use for the new Space. Defaults to the same hardware tier as the original Space. Options include "cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large", subject to availability.
            secrets: A dictionary of (secret key, secret value) to pass to the new Space. Defaults to None. Secrets are only used when the Space is duplicated for the first time, and are not updated if the duplicated Space already exists.
            sleep_timeout: The number of minutes after which the duplicate Space will be puased if no requests are made to it (to minimize billing charges). Defaults to 5 minutes.
            max_workers: The maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously.
            verbose: Whether the client should print statements to the console.
        Example:
            import os
            from gradio_client import Client
            HF_TOKEN = os.environ.get("HF_TOKEN")
            client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN)
            client.predict("audio_sample.wav")
            >> "This is a test of the whisper speech recognition model."
        r1   r7   z9. If it is a private Space, please provide an `hf_token`.Nr6   r?   zUsing your existing Space: u    🤗zSecrets are only used when the Space is duplicated for the first time, and are not updated if the duplicated Space already exists.zCreating a duplicate of u    for your own use... 🤗T)from_idto_idr1   r5   privatezCreated new Space: z1-------
NOTE: this Space uses upgraded hardware: zG... see billing info at https://huggingface.co/settings/billing
-------<   )rH   timeout_in_secondsr<   )rH   rB   rG   )huggingface_hubget_space_runtimer   rT   r   get_full_repo_namer]   r   	SPACE_URLr   warningswarnduplicate_spacer   add_space_secrethardwarer   	CPU_BASICrequest_space_hardwareset_space_timeout)clsr   r   rH   r   r   secretssleep_timeoutrB   rG   original_infornferK   keyvaluecurrent_infocurrent_hardwarer   s                     r   r&   zClient.duplicateT  sm   j	+==gXVM
 e|C(+&99%xPH&99c"1%XH	P--hhG1%//2H2H2R1SSXY " Y( '88R!!L_%B%B%L%L 	 5}55x'228XXVDXJ  OW  X
 44>>>##8PR@R "Ix['
 y ' 	(	1jk	, ' 	P0	9RST++ ""/'--/ JC#44 #uH +EOO,B,B8,L+MNO!	Ps+   F 5AG  	F=(F88F= BIIc                    | j                   sy t        j                  | j                   | j                        }|j                  S Nr   )rK   r   r   rH   stage)r   infos     r   r[   zClient._get_space_state  s0    }}00dmmTzzr   api_namer   c               l    | j                  ||        | j                  |||d|j                         S )a  
        Calls the Gradio API and returns the result (this is a blocking call). Arguments can be provided as positional arguments or as keyword arguments (latter is recommended).

        Parameters:
            args: The positional arguments to pass to the remote API endpoint. The order of the arguments must match the order of the inputs in the Gradio app.
            api_name: The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint.
            fn_index: As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence.
            kwargs: The keyword arguments to pass to the remote API endpoint.
        Returns:
            The result of the API call. Will be a Tuple if the API has multiple outputs.
        Example:
            from gradio_client import Client
            client = Client(src="gradio/calculator")
            client.predict(5, "add", 4, api_name="/predict")
            >> 9.0
        r  )_infer_fn_indexr$   result)r   r  r   argskwargss        r   r#   zClient.predict  s=    . 	Xx0t{{Hx
;A

&(	r   c                    t        t               t               | j                  |   j                  | j
                        S r   )r   r
   r   r   process_predictionsr|   )r   r   s     r   
new_helperzClient.new_helper  s2    FKNN8$88NN	
 	
r   )r  r   result_callbacksc                   | j                  ||      }| j                  |   }t        |t              r!t	        j
                  |j                  ||      }d}|j                  dv r| j                  |      }|j                  |      }	 | j                  j                  |	g| }
|j                  |      }t        |
|| j                  | j                  |      }|r5t        |t               r|g}dd}|D ]  }|j#                   ||              |S )a  
        Creates and returns a Job object which calls the Gradio API in a background thread. The job can be used to retrieve the status and result of the remote API call.
         Arguments can be provided as positional arguments or as keyword arguments (latter is recommended).

        Parameters:
            args: The arguments to pass to the remote API. The order of the arguments must match the order of the inputs in the Gradio app.
            api_name: The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint.
            fn_index: As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence.
            result_callbacks: A callback function, or list of callback functions, to be called when the result is ready. If a list of functions is provided, they will be called in order. The return values from the remote API are provided as separate parameters into the callback. If None, no callback will be called.
            kwargs: The keyword arguments to pass to the remote API endpoint.
        Returns:
            A Job object that can be used to retrieve the status and result of the remote API call.
        Example:
            from gradio_client import Client
            client = Client(src="gradio/calculator")
            job = client.submit(5, "add", 4, api_name="/predict")
            job.status()
            >> <Status.STARTING: 'STARTING'>
            job.result()  # blocking call
            >> 9.0
        N)r:   r=   sse_v1sse_v2sse_v2.1r   )communicatorrG   rK   
_cancel_fnc                      fd}|S )Nc                    t        | j                         t              r | j                           y  | j                                y r   )rM   r  tuple)futurecallbacks    r   fnz,Client.submit.<locals>.create_fn.<locals>.fn3  s/    !&--/59 &--/2 1r   r   )r$  r%  s   ` r   	create_fnz Client.submit.<locals>.create_fn2  s    2 	r   )returnr   )r  r   rM   r   r   construct_argsparameters_infor9   r  make_end_to_end_fnr   r$   make_cancelJobrG   rK   r   r   )r   r  r   r  r  r  inferred_fn_indexendpointhelperend_to_end_fnr#  	cancel_fnjobr&  r$  s                  r   r$   zClient.submit  s   : !008D>>"34h)''(@(@$OD !
 
 __%67F 33F;%%%m;d;((0	LL]] 
 *H5$4#5  - ;%%i&9:; 
r   c                   t         j                  j                  | j                  t        j
                        }| j                  t        j                  d      kD  rt        j                  |f| j                  | j                  | j                  d| j                  }|j                  r|j!                         }nt#        d| j$                   d|j&                         t        j(                  t        j*                  fdt!        j,                  | j.                        ddi| j                  }|j                  r|j!                         d   }n%t#        d| j$                   d|j&                         |d	   j1                         D ci c]  \  }}|j3                  d
d      s|| c}}|d	<   |d   j1                         D ci c]  \  }}|j3                  d
d      r|| c}}|d<   |S c c}}w c c}}w )Nz3.36.1r   zCould not fetch api info for : r   F)rd   	serializeapinamed_endpointsshow_apiTunnamed_endpoints)rg   rh   ri   rk   r   RAW_API_INFO_URLr}   r   Versionr   re   r*   rL   r,   ra   
is_successr   rT   rZ   textr   SPACE_FETCHER_URLdumpsrd   r   pop)r   api_info_urlrr  fetchar   s          r   r~   zClient._get_api_info@  s   ||++D,=,=u?U?UVgooh77			
 ##A ||vvx #@
"QVVH!UVVJJ'' #jj5!& ##E zz|E* 3DHH:R

|L  ""34::<#
QjRV@WAqD#

 01779%
1uuZ& qD%
 !
 #
%
s   
G/%G/G5c                   t        | j                  d         }t        | j                  d         }|dk(  r|d}d}|d| dz  }| j                  d   j                         D ]  \  }}|| j                  ||      z  } |rM|d	| dz  }| j                  d   j                         D ]#  \  }	}|| j                  t	        |	      |      z  }% n|dkD  r	|d	| d
z  }|rt        |       |dk(  r|S |dk(  r| j                  S y)au  
        Prints the usage info for the API. If the Gradio app has multiple API endpoints, the usage info for each endpoint will be printed separately. If return_format="dict" the info is returned in dictionary format, as shown in the example below.

        Parameters:
            all_endpoints: If True, prints information for both named and unnamed endpoints in the Gradio app. If False, will only print info about named endpoints. If None (default), will print info about named endpoints, unless there aren't any -- in which it will print info about unnamed endpoints.
            print_info: If True, prints the usage info to the console. If False, does not print the usage info.
            return_format: If None, nothing is returned. If "str", returns the same string that would be printed to the console. If "dict", returns the usage info as a dictionary that can be programmatically parsed, and *all endpoints are returned in the dictionary* regardless of the value of `all_endpoints`. The format of the dictionary is in the docstring of this method.
        Example:
            from gradio_client import Client
            client = Client(src="gradio/calculator")
            client.view_api(return_format="dict")
            >> {
                'named_endpoints': {
                    '/predict': {
                        'parameters': [
                            {
                                'label': 'num1',
                                'python_type': 'int | float',
                                'type_description': 'numeric value',
                                'component': 'Number',
                                'example_input': '5'
                            },
                            {
                                'label': 'operation',
                                'python_type': 'str',
                                'type_description': 'string value',
                                'component': 'Radio',
                                'example_input': 'add'
                            },
                            {
                                'label': 'num2',
                                'python_type': 'int | float',
                                'type_description': 'numeric value',
                                'component': 'Number',
                                'example_input': '5'
                            },
                        ],
                        'returns': [
                            {
                                'label': 'output',
                                'python_type': 'int | float',
                                'type_description': 'numeric value',
                                'component': 'Number',
                            },
                        ]
                    },
                    '/flag': {
                        'parameters': [
                            ...
                            ],
                        'returns': [
                            ...
                            ]
                        }
                    }
                'unnamed_endpoints': {
                    2: {
                        'parameters': [
                            ...
                            ],
                        'returns': [
                            ...
                            ]
                        }
                    }
                }
            }

        r7  r9  r   NTz8Client.predict() Usage Info
---------------------------
zNamed API endpoints: r   z
Unnamed API endpoints: z3, to view, run Client.view_api(all_endpoints=True)
rN   dict)r   r   r   _render_endpoints_infointr]   )
r   all_endpoints
print_inforeturn_formatnum_named_endpointsnum_unnamed_endpoints
human_infor  endpoint_infor   s
             r   r%   zClient.view_apig  sX   V "$**->"?@ #DJJ/B$C D!#(= MQ
-.A-B"EE
'+zz2C'D'J'J'L 	O#Hm$55hNNJ	O 56K5LBOOJ+/::6I+J+P+P+R X'- d99#h-WW
X #Q&56K5L  MA  B  BJ*E!f$:: %r   c                |    t        t        j                               | _        | j                  j                          y r   )rN   r   r   r   r   r   r   s    r   reset_sessionzClient.reset_session  s'    

-##%r   c                    | j                   s|S 	 ddlm} |j                  j                         }|r,t        |d      r d|j                  v r|j                  d   |d<   |S # t        $ r |cY S w xY w)a  
        Adds the x-ip-token header to the headers dictionary to pass it to a Zero-GPU Space. This allows a user's
        ZeroGPU quota to be tracked and used by the underlying Space. For the x-ip-token header to be present,
        this method needs to be called when a Gradio app's LocalContext is defined. i.e. this method
        cannot be called when the Gradio Client is instantiated, but must be called from inside a Gradio app's
        prediction function.
        r   )LocalContextr*   z
x-ip-token)rK   gradio.contextrS  ImportErrorrequestre   hasattrr*   )r   r*   rS  rV  s       r   r   zClient.add_zero_gpu_headers  su     }}N	3
 &&**,ww	2|w7V$+OOL$AGL! 	 N	s   A   A.-A.c                   |d   }|D cg c]  }|j                  d      xs |d    }}|D cg c]  }t        j                  |       }}dj                  |      }|r|dz   }|d   D cg c]  }|d   	 }}|D cg c]  }t        j                  |       }}dj                  |      }	t	        |      dkD  rd|	 d}	t        |t              rd	| d
}
n!t        |t              rd| }
nt        d      d| |
 d|	 d}|dz  }|r|D ]  }|d   j                  d      rd|d   d    dnd}|j                  d      }t        j                  |d t        j                        }|j                  dd      sdnd| d}|d   d   }|j                  dd      r||dz  }|d|d    dt        j                  |j                  d      xs |d          d | d!| d!| d"z  } n|d#z  }|d$z  }|d   r`|d   D ]V  }|d   j                  d      rd|d   d    dnd}|d   d   }|d|d    dt        j                  |d          d | | d"z  }X |S |d#z  }|S c c}w c c}w c c}w c c}w )%N
parametersparameter_namelabel, returnsr?   ()z
api_name=""z	fn_index=z)name_or_index must be a string or integerz
 - predict(z) -> r   z    Parameters:
python_typedescriptionz (r<   parameter_defaultc                    d| d    dS )Nzhandle_file("r   z")r   xs    r   <lambda>z/Client._render_endpoints_info.<locals>.<lambda>  s    ahZr: r   parameter_has_defaultFz
(required)z(not required, defaults to:   typez | Nonez     - [	componentz] r4   z 
z     - None
z    Returns:
)re   r   sanitize_parameter_namesr   r   rM   rN   rH  rT   traverseis_file_obj_with_meta)r   name_or_indexendpoints_infoparameter_infopparameter_namesrendered_parametersreturn_valuesrB  rendered_return_valuesfinal_paramrN  r  descdefault_valuedefault_infotype_s                    r   rG  zClient._render_endpoints_info  s   
 (5;I
67AEE"#1qz1
 
 GVV599!<VV"ii8"5"<-;I-FG7GGDQRq77:RR!%=!9}!'()?(@%B"mS)&}oQ7Ks+%m_5KHII$%8$9+eLbKccef
))
& n M*..}= m,];<A> 
 !%)< = %!://!  88$;UC !9-J 
 ]+F3883U;@UY&Ek):(;2e>\>\]a]e]efv]w  ^I{  AH  |I  ?J  >K  KM  NS  MT  TU  Vb  Uc  cd  ei  dj  jm  n  n
)n, /)J&&
)$&y1 @ M*..}= m,];<A> 
 ]+F3k):(;2e>\>\]abi]j>k=llnotnuvzu{{~
@  /)Jw
 W HRs   II#,I(>I-c                (    | j                  dd      S NFrN   )rJ  rK  r%   r   s    r   __repr__zClient.__repr__)      }}U}CCr   c                (    | j                  dd      S r}  r~  r   s    r   __str__zClient.__str__,  r  r   c                z    d| j                   i}	 t        ddt        j                  |       y # t        $ r Y y w xY w)NrZ   zpy_client/initiatedr0   )topicr2   r3   
user_agent)rZ   r   r   rI   	Exception)r   r   s     r   r   zClient._telemetry_thread/  sG     488
	+, % 1 1	  		s   . 	::c                   d }||t        | j                  d         D ]:  \  }}|j                  d      }||du rd|z   |k(  s'|j                  d|      } |S  d| d}|j                  d      s|dz  }t	        |      |:|}|| j
                  vs| j
                  |   j                  st	        d	| d      |S | j
                  j                         D cg c]4  }|j                  r&|j                  |j                  |j                  r|6 }	}t        |	      d
k(  r|	d   j                  }|S t	        d      c c}w )Nr@   r  Fr6   rA   z(Cannot find a function with `api_name`: .z% Did you mean to use a leading slash?zInvalid function index: r?   r   zYThis Gradio app might have multiple endpoints. Please specify an `api_name` or `fn_index`)r   rd   re   rW   rT   r   is_validr   r  
backend_fnr8  r   r   )
r   r  r   r-  idconfig_api_nameerror_messager   valid_endpointss
             r   r  zClient._infer_fn_index>  s    !$++n"=> 01"#%%
"3"*o.F(H4()dA%8 ! E0 #K8*TU V**3/!%LLM //! (!7~~&78AA #;H:Q!GHH  !  ..0::JJ*LL,JJ O  ?#q($3A$6$?$?!
 !  !o s   9D>c                V    t        | d      r| j                  j                  d       y y )Nr   T)wait)rW  r   shutdownr   s    r   __del__zClient.__del__e  s&    4$MM"""- %r   c                X    t        j                  || j                        j                  S r  )r   
space_inforH   host)r   spaces     r   rY   zClient._space_name_to_srci  s    ))%t}}EJJJr   c                   t        j                  t        j                  j	                  | j
                  t        j                        f|d   |d   d| j                  d| j                  }|j                  sA|j                  dk(  rt        d| j
                   d      t        d| j
                   d      |j                  j                         D ci c]  \  }}|	|| c}}| _        y c c}}w )	Nr   r?   )usernamepassword)r   r     zCould not login to z. Invalid credentials.r  )r   r   rg   rh   ri   rZ   r   	LOGIN_URLr,   ra   r<  r   r   rT   rL   r   )r   r   r   namer  s        r   rb   zClient._loginl  s    zzLL  5??;
"1g47;??
 	
 3&))$((3IJ  !#6txxj!BCC+/<<+=+=+?
'D%5CTD%K
 
s   
C1"C1c                   t        j                  t        j                  j	                  | j
                  t        j                        f| j                  | j                  | j                  d| j                  }|j                  r|j                         S |j                  dk(  rt        d| j
                   d      |j                  dk(  rt        j                   d      d t        j                  | j
                  f| j                  | j                  | j                  d| j                  }|j                  st#        d| j
                         t%        j&                  d|j(                        }	 t        j*                  |j-                  d	            }d|v rt#        d      |S # t.        $ r}t#        d
| j
                         |d }~ww xY w)Nr   r  zCould not load z0 as credentials were not provided. Please login.i  z5Too many requests to the API, please try again later.zCould not fetch config for z+window.gradio_config = (.*?);[\s]*</script>r?   z"Could not get Gradio config from: allow_flaggingzcGradio 2.x is not supported by this client. Please upgrade your Gradio app to Gradio 3.x or higher.)r   re   rg   rh   ri   rZ   r   
CONFIG_URLr*   rL   r,   ra   r<  r   r   r   TooManyRequestsErrorrT   researchr=  r   groupAttributeError)r   rB  r  rd   aes        r   rc   zClient._get_config~  s   IILL  5+;+;<
LLLL??	

 
 <<668O]]c!%!$((+[\  ]]c!,,G 			
 ##A << #>txxj!IJJYYMqvvVFFLLO4
  6) y  M "  8
Cs   3$F( (	G1G

Gc                8	   t        j                  d       | j                  d   dk(  rsdgt        t              xr	 d D        }|st        d       t              dk7  rt        d	      t              D ]  \  }}t        |t              s||f|<    t        fd
| j                  j                         D        d      }	|	s/t        dd   d    d| j                  xs | j                         |	j                  D 
cg c]  }
|
j                  r|
 }}
|	j                  D 
cg c]  }
|
j                  r|
 }}
|dgk(  s|dgk(  rt        d| d|       d}| j                  rFt!        j"                  | j                        j$                  }|r|st        d| j                   d      |r0d|v r|j'                  d      d   }t!        j(                  ||      }n]| j                  r"| j                  j'                  d      d    d}ndt+        j,                  d       }t!        j(                  ||      }t!        j.                         }	 t!        j"                  |       d}t!        j4                  |dd|d|       |rt!        j6                  |dddgi       t9        t        t;        t<              j>                  d z  d!z        d"#      5 }|jA                         }ddd       jC                  d$| j                        }|jC                  d%d   d         }|jC                  d&d   d         }tE        jF                  d'dd"(      5 }tE        jF                  d'd)      5 }|jI                  |       |jI                  d*jK                  d+g             ddd       ddd       tM        d,jN                  -      tM        d.jN                  -      g}|jQ                  |d/d||0       |rt!        jR                  |d1||       |rt!        jR                  |d2||       d3| }tU        d4|        |S c c}
w c c}
w # t         j0                  j2                  $ r d}Y w xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)5a  
        Deploy the upstream app as a discord bot. Currently only supports gr.ChatInterface.
        Parameters:
            discord_bot_token: This is the "password" needed to be able to launch the bot. Users can get a token by creating a bot app on the discord website. If run the method without specifying a token, the space will explain how to get one. See here: https://huggingface.co/spaces/freddyaboulton/test-discord-bot-v1.
            api_names: The api_names of the app to turn into bot commands. This parameter currently has no effect as ChatInterface only has one api_name ('/chat').
            to_id: The name of the space hosting the discord bot. If None, the name will be gradio-discord-bot-{random-substring}
            hf_token: HF api token with write priviledges in order to upload the files to HF space. Can be ommitted if logged in via the HuggingFace CLI, unless the upstream space is private. Obtain from: https://huggingface.co/settings/token
            private: Whether the space hosting the discord bot is private. The visibility of the discord bot itself is set via the discord website. See https://huggingface.co/spaces/freddyaboulton/test-discord-bot-v1
        zThis method is deprecated and may be removed in the future. Please see the documentation on how to create a discord bot with Gradio: https://www.gradio.app/guides/creating-a-discord-bot-from-a-gradio-appmodechat_interface)chatr  c              3     K   | ]P  }t        |t              xs: t        |t              xr( t        |d    t              xr t        |d   t               R yw)r   r?   N)rM   rN   r"  ).0ns     r   	<genexpr>z(Client.deploy_discord.<locals>.<genexpr>  sW      6

 	 q# 1e$XAaD#)>X:aPQdTWCX6
s   AANzPEach entry in api_names must be either a string or a tuple of strings. Received r?   z7Currently only one api_name can be deployed to discord.c              3  R   K   | ]  }|j                   d d   d    k(  r|   yw)r6   r   N)r  )r  ep	api_namess     r   r  z(Client.deploy_discord.<locals>.<genexpr>  s5      ;;Ail1o%6"77 s   $'z	api_name r   z not present in textboxz[Currently only api_names with a single textbox as input and output are supported. Received z and FzSince zo is private, you must explicitly pass in hf_token so that it can be added as a secret in the discord bot space.r6   r   z-gradio-discord-botzgradio-discord-bot-   Tr  r"   )	repo_type	space_sdkr1   r5   r   tagszgradio-discord-bot)repo_idr  metadata	templateszdiscord_chat.pyr   )encodingz<<app-src>>z<<api-name>>z<<command-name>>w)r  deleter  )r  r  r   zdiscord.py==2.3.1zapp.py)path_in_repopath_or_fileobjzrequirements.txtzDeploy Discord Bot)r  commit_messager  
operationsr1   DISCORD_TOKENHF_TOKENzhttps://huggingface.co/spaces/zSee your discord bot here! )+r   r   rd   rM   listrT   r   r   rN   nextr   r   rK   rZ   input_component_typesskipr   r  r   r   r   r  	token_hexHfApir   r   create_repometadata_updateopenr	   __file__parentreadrv   tempfileNamedTemporaryFilewriter   r   r  create_commitr   r]   )r   discord_bot_tokenr  r   rH   r   
valid_listr  r  r%  inpinputsoutputs
is_privaterK   r6  first_uploadfappapp_filerequirementsr  r   s     `                    r   r'   zClient.deploy_discord  s   " 	 Z	
 ;;v"229)*I	40 
 6

 6

 Jbclbmn  y>QVWW + 	,GAt$$ $d|	!	, ..//1
 
 IaLO,,<T]]=Vdhh<WX  "$!9!9J##JJ"$":":K3#((3KK)$YK)?"85	3 
 
==(33DMMBJJJ( T]]O ,T T 
 e|C(+&99%xPH}}"mm11#6q9::MN01B1B11E0FG&99((SH##%	 &&x0 L 	##	
 ++ ! #7"89 X%%36GGH
 	 &&(C		
 kk-2kk.)A,q/:kk,il1o>((UW
 	E,,#eD Es#""499.A-B#CDE	E HhmmT/ARAR

 	/! 	 	
 ,,/+<H ,,	 /xj9+C512
A KK@ $$<< 	 L	 $	 	E E	E 	EsZ   QQ1QQQ  Q7R53R(RQ43Q47RR		RR)F(   TNN)rZ   rN   rH   str | Literal[False] | NonerB   rH  rG   boolr   ztuple[str, str] | Nonera   zdict[str, Any] | Noner*   dict[str, str] | Noner+   zstr | Path | Literal[False]r,   r  r-   r  r.   r  )r9   1Literal['sse_v1', 'sse_v2', 'sse_v2.1', 'sse_v3']r'  None)NFTNNr   r  T)r   rN   r   
str | NonerH   r  r   r  r   z}Literal['cpu-basic', 'cpu-upgrade', 't4-small', 't4-medium', 'a10g-small', 'a10g-large', 'a100-large'] | SpaceHardware | Noner  r  r  rH  rB   rH  rG   r  )r  r  r   
int | Noner'  r   )r   rH  r'  r   )r  r  r   r  r  z Callable | list[Callable] | Noner'  r,  )NTN)rI  zbool | NonerJ  r  rK  zLiteral['dict', 'str'] | Noner'  zdict | str | None)r'  r  )r*   dict[str, str]r'  r  )ro  z	str | intrp  zdict[str, list[ParameterInfo]]r'  rN   )r  r  r   r  r'  rH  )r'  r  )r   ztuple[str, str])r'  rF  )NNNFF)
r  r  r  z"list[str | tuple[str, str]] | Noner   r  rH   r  r   r  )__name__
__module____qualname____doc__rV   r   r   r   r   r   classmethodr&   r[   r#   r  r$   r~   r%   rQ  r   rG  r  r  r   r  r  rY   rb   rc   r'   r   r   r   r)   r)   :   s   & 16'+.2H1 *.6F!%"&H1H1 .H1 	H1
 H1 %H1 ,H1 'H1 4H1 H1 H1  H1T'.@I@	@DB  !05 )-)rr r .	r
 r
r" '#r$ %r& 'r( )r rh  $#	  	 
8
  $#=AK K 	K
 ;K 
KZ%R &*7;	d"d d 5	d
 
dL&*A A 7A 
	AFDD%!N.K
$(X )-8< 05U%U 6U 	U
 .U Ur   r)   c                  ,    e Zd ZU ded<   ded<   ded<   y)ComponentApiTyper  r  value_is_fileis_stateNr  r  r  __annotations__r   r   r   r  r  @  s    
JNr   r  c                      e Zd ZU ded<   y)	ReplaceMerH  indexNr  r   r   r   r  r  G  s    Jr   r  c                      e Zd ZdZ	 d	 	 	 	 	 	 	 ddZddZddZedd       Zd Z	d Z
ddd	Z	 	 dd
ZdddZddZddZd ZddZddZddZddZd dZd!dZ	 	 	 	 	 	 d"dZy)#r   zIHelper class for storing all the information about a single API endpoint.c                Z   || _         || _        || _        |j                  d      }t	        |t
              rd|z   n|| _        | j                   j                  | _        || _        |d   D cg c]  }| j                  |       c}| _
        |d   D cg c]  }| j                  |       c}| _        | j                         | _        | j                   j                  | _        | j                  du| _        |j                  d      | _        |j                  d      | _        y c c}w c c}w )Nr  r6   r  r  Fr  r8  )r   r   r   re   rM   rN   r  r   r9   _get_component_typer  output_component_types_get_parameters_infor)  rk   root_urlr  r  r8  )r   r   r   r   r9   r  id_s          r   r   zEndpoint.__init__O  s    % $>>*-(37C(NX 	 [[&&
 5?5I&
.1D$$S)&
" 6@	5J'
.1D$$S)'
#  $88:00 U2$..6"z2&
'
s   ,D#D(c                    t        fd| j                  j                  d   D              }|j                  d|d   t        j
                  v       }t        || j                  |      |d   dk(        S )Nc              3  4   K   | ]  }|d    k(  s|  ywrA   Nr   )r  r  component_ids     r   r  z/Endpoint._get_component_type.<locals>.<genexpr>j  s!      
1T7l;RA
s   
componentsskip_apiri  r   )r  r   rd   re   r   SKIP_COMPONENTSr  r  )r   r  rj  r  s    `  r   r  zEndpoint._get_component_typei  sv     
{{)),7
 
	 ==Yv->%BWBW-WXy)f(
 	
r   c                x    | j                   | j                  d   v r| j                  d   | j                      d   S y )Nr7  rY  )r  r   r   s    r   r  zEndpoint._get_parameters_infot  s9    ==DJJ'899::/0?MMr   c                <    d| vryt        j                  | d         S )Napi_infoF)r   r  )rj  s    r   r  zEndpoint.value_is_filey  s%     Y&""9Z#899r   c                h    d| j                   j                   d| j                   d| j                   S )NzEndpoint src: z, api_name: z, fn_index: )r   rZ   r  r   r   s    r   r  zEndpoint.__repr__  s0    0T]]O<X\XeXeWfggr   c                "    | j                         S r   )r  r   s    r   r  zEndpoint.__str__  s    }}r   Nc                <      j                         fd}|S )Nc                    j                   st        j                         j                  j                  r j
                  |  }  j                  |  }  |  } j                  | }rRj                  5  j                  j                  s%j                  j                  j                  |       d d d        |S |S # 1 sw Y   |S xY wr   )r  r   InvalidAPIEndpointErrorr   r-   insert_empty_stateprocess_input_filesr  lockr2  r  r   )r   predictions_predictr/  r   s     r   _innerz+Endpoint.make_end_to_end_fn.<locals>._inner  s    ==3355{{++.t..5+4++T2D"D/K2$22K@K [[ ?!::--

**11+>? ;? s   8<C  C
)make_predict)r   r/  r  r  s   `` @r   r*  zEndpoint.make_end_to_end_fn  s    $$V,	$ r   c           	     8   	
 y  j                   j                  t        j                  d      kD  rNt        j
                  j                   j                   j                  t        j                         fdd 	d
ng }t         j                   j                  d         D ]K  \  }} j                  |d   v s|j                  ||d   D cg c]  }| j                  k7  s| c}f       M |rt        |d       nd\  }d u
d 	
rS|rQ|D cg c]0  }d	 j                   j                  d   |   j                  d
      z   2 }}ddj!                  |       d	n
sd	 fd j                   j"                  	
 fd}|S c c}w c c}w )Nz4.29.0c                 `    j                   j                  j                   j                  dS )N)r   r   r   )r   r   r   r   )r/  r   s   r   	post_dataz'Endpoint.make_cancel.<locals>.post_data  s(     $$(KK$<$< & r   Tr@   cancelsc                    t        | d         S )Nr?   )r   re  s    r   rg  z&Endpoint.make_cancel.<locals>.<lambda>  s    c!A$i r   )r  )NNr6   r  z1Cancelled this job will also cancel any jobs for r\  z that are currently running.zCancelling this job will not stop the server from running. To fix this, an event must be added to the upstream app that explicitly cancels this one or the upstream app must be running Gradio 4.29.0 and greater.c                 8    g  j                   j                  dS )Nr   r   r   )r   r   )r   r   s   r   r  z'Endpoint.make_cancel.<locals>.post_data  s      ($(KK$<$< r   c                     rt        j                          rqt        j                  f        j                  j
                  j                  j                  j                  j                  dj                  j                   y y )Nr   )	r   r   r   r   r   r*   rL   r,   ra   )
cancel_msgcancellabler  r   r   s   r   _cancelz%Endpoint.make_cancel.<locals>._cancel  sn    j)

" KK// KK//;;11 kk.. r   )r   r}   r   r;  rg   rh   ri   rk   r   
CANCEL_URLr   rd   r   r   minre   r   rm   )r   r/  
candidatesr  depr  other_cancelledother_api_namesr  r  r  r   r  r   s   ``       @@@@@r   r+  zEndpoint.make_cancel  s    >;;""W__X%>>,,&&t{{'?'?AQAQRC JK68J#DKK$6$6~$FG 3==C	N2%%IM1!t}}:LQMN =GJ$78L &Ho #$.KJ -# $++,,^<Q?CCJOO# #
 H		RaHbGc d2 2  !R  ++%%C	 	 ] N#s   F)F5Fc                     d fd}|S )Nc                 2   | 	j                   	j                  j                  d} 	j                   	j                  j                  d}	j                  dk(  r	j	                  | |      }n	j                  dv r	j                  j                  | |	j                        }	j                  j                  j                  |       g 	j                  j                  |<   |_	        	j                  |	j                        }nt        d	j                         d|v r.|d   t        d      |j                  d      }t        dd|i|	 |d	   }t+        |      S # t        $ r}	j                  j                  xr4 t!        j"                  	j                  j                        j$                   }d|v r7d
|d   v r0|r.t'        j(                  d	j                  j                   d      d d|v rt        |d         d t        d|       |d }~ww xY w)Nr  )r   r   r=   )r  r  r  r   zUnsupported protocol: errorzThe upstream Gradio app has raised an exception but has not enabled verbose error reporting. To enable, set show_error=True in launch().r   r   429zToo many requests to the API, please try again later. To avoid being rate-limited, please duplicate the Space using Client.duplicate(z&) and pass in your Hugging Face token.z:Could not find 'data' key in response. Response received: r   )r   r   r   r9   
_sse_fn_v0r   r   addr   r   _sse_fn_v1plusrT   r   r@  KeyErrorrK   r   r  r   r   r  r"  )
r   r   r  r   r   outputkeis_public_spacer/  r   s
           r   r  z'Endpoint.make_predict.<locals>._predict  s    MM $ 8 8D !MM $ 8 8I
 }}%y&A"LL;;00y$--P--11(;CE66x@"*,,VXt}}M #9$--!IJJ& '?*"_ 
 %jj1G"=7=f==" = !  KK(( U+66t{{7K7KLTTT   f$&/)Ao44MMQ[[MaMaLb c?@  	 
 &$VG_54?PQWPXYs   E 	H(B)HHr'  r"  r   )r   r/  r  s   `` r   r  zEndpoint.make_predict  s    3	!j r   c                    t        |      }t        | j                        D ]$  \  }}|j                  s|j	                  |d        & t        |      S r   )r  r   r  r  insertr"  )r   r   r  input_component_types       r   r  zEndpoint.insert_empty_state!  sN    Dz'01K1K'L 	%#A##,,At$	% T{r   c                    g }t        |      D ]P  \  }}t        j                  |t        | j                  |      t        j
                        }|j                  |       R t        |      S )N)
data_index)r   r   rm  r   _upload_filern  r   r"  )r   r   data_r  r  s        r   r  zEndpoint.process_input_files(  sa    dO 	DAq))a8++A
 LLO	 U|r   c                    | j                   j                  r | j                  | }| j                   j                  r | j                  | } | j                  | }|S r   )r   r+   r-   remove_skipped_componentsreduce_singleton_output)r   r  s     r   r  zEndpoint.process_predictions3  sZ     ;;%%-$--{;K;;''8$88+FK2d22K@r   c                2   t        |      }| j                  j                  dk(  r:t        j                  || j
                  t        j                        }t        |      S t        j                  || j
                  t        j                        }t        |      S )Nr  )	r  r   r9   r   rm  _download_filern  is_file_objr"  )r   r   r5  s      r   r+   zEndpoint.download_files>  st    T
;;:-NNt**E,G,GE
 U| NN5$*=*=u?P?PQEU|r   c                    t        || j                  d      D cg c]  \  }}|j                  s| }}}t        |      S c c}}w )r<   F)strict)zipr  r  r"  )r   r   r  octs       r   r7  z"Endpoint.remove_skipped_componentsH  sL     dD$?$?N
388 
 

 T{
s   Ac                    | j                   j                  r'| j                  D cg c]  }|j                  r| }}n| j                  }t	        |      dk(  r|d   S |S c c}w )Nr?   r   )r   r-   r  r  r   )r   r   oeffective_output_componentss       r   r8  z Endpoint.reduce_singleton_outputQ  se    ;;''66+aff+' + +/*E*E'*+q07NK+s
   AAc                   |d   }t        |      }t        j                  |      s| j                  d   |   t	        fd| j
                  j                  d   D        i       }| j
                  j                  j                  dd       }|t        j                  n|}t        j                  j                  |      |kD  r(t        d| d| d|j                  d	d
      d
z    d      t        |d      5 }d|j                  |ffg}t!        j"                  | j
                  j$                  f| j
                  j&                  | j
                  j(                  | j
                  j*                  |d| j
                  j,                  }	d d d        	j/                          |	j1                         }
|
d   }|t        j2                  |j                        ddidS # 1 sw Y   SxY w)NrP   r  c              3  2   K   | ]  }|d    k(  r|  ywr  r   )r  cr  s     r   r  z(Endpoint._upload_file.<locals>.<genexpr>c  s%      w,. s   r   max_file_sizezFile z" exceeds the maximum file size of z bytes set in r[  r<   z component.rbfiles)r*   rL   r   rH  r   _typezgradio.FileData)rP   	orig_namemeta)r	   r   is_http_url_liker   r  r   rd   re   mathinfrO   rP   getsizerT   r  r  r   r   rz   r*   rL   r,   ra   r   r   !strip_invalid_filename_characters)r   r  r3  	file_pathrJ  component_configrF  f_rH  rB  r  r  s              @r   r4  zEndpoint._upload_file]  s   fI	O	%%i0??84Z@L#![[//=
   !KK..22?DIM(5(=DHH=Mwwy)M9 I;&H X.227B?"DE[R  i& 	"!INNB#789JJKK** KK// KK//;;11 kk..	  VVXFq	I @@P/0
 	
	 	s   6BGG"c                   | j                   dz   |d   z   }| j                  j                  +t        j                  | j                  j                  d       t        j                         }t        t        j                               t        j                  d      z  }|j                  dd       t        j                  d|f| j                  j                  | j                  j                   | j                  j"                  dd| j                  j$                  5 }|j'                          t)        |t        |      j*                  z  d	      5 }|j-                  d
|j.                  z        D ]$  }|j1                  |       |j3                  |       & 	 d d d        d d d        t        | j                  j                        |j5                         z  }|j                  dd       |t        |      j*                  z  }	t7        j8                  |t        |      j*                  z  |	       t;        |	j=                               S # 1 sw Y   xY w# 1 sw Y   xY w)Nzfile=rP   Tr4   r   )r5   parentsr   )r*   rL   r   follow_redirectswb   )
chunk_size)r  r   rU   rO   rR   hashlibsha256r	   r  
gettempdirr  r  mkdirr   r   r*   rL   r,   ra   r   r  r  r   
block_sizerJ   r  	hexdigestshutilmoverN   resolve)
r   rf  url_pathshatemp_dirr   r  r   	directorydests
             r   r:  zEndpoint._download_file  s   ==7*QvY6;;!!-KK..>nn++-.1B1B21FFd3\\
 KK''KK'';;))!
 kk&&
 	# %%'hh!4!44d; #q%00C#..<P0Q #EJJu%GGEN##	# //03==?B	t44>...HtH~222D94<<>""# #	# 	#s%   3IAIII	IIc                   t        j                  dt        j                  d       | j                  j                  d| j                  j
                  5 }t        j                  ||||| j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  | j                  j                  
      cd d d        S # 1 sw Y   y xY w)Nr   )r   r   r   )r   r)   r   r   r,   ra   r   get_pred_from_sse_v0rp   ru   r*   rL   r   )r   r   r   r/  r   s        r   r'  zEndpoint._sse_fn_v0  s    \\ 
MM$/;;))
 kk&&
 	 --##((####&&$$	 	 	s   BC55C>c           
        t        j                  || j                  j                  | j                  j                  | j                  j
                  ||| j                  j                  | j                  j                        S r   )r   get_pred_from_sse_v1plusr   r*   rL   r   r,   r   )r   r/  r   r9   s       r   r)  zEndpoint._sse_fn_v1plus  sa     --KKKKKK22KK""KK  	
 		
r   )r  )r   r)   r   rH  r   rF  r9   rN   )r  rH  )r'  zlist[ParameterInfo] | None)rj  rF  r'  r  r   )r/  Communicator | Noner.  )r'  r   )r  rF  r3  rH  r'  r  )rf  rF  r'  rN   )r   rF  r   rF  r/  r   )r/  r   r   rN   r9   r  )r  r  r  r  r   r  r  staticmethodr  r  r  r*  r+  r  r  r  r  r+   r7  r8  r4  r:  r'  r)  r   r   r   r   r   L  s    S PX33(+39=3IL34	

 : :h.G#GR6p		
'
R#<&

 
 D	
r   r   r  r  statusc                  x     e Zd ZdZ	 	 	 	 d
	 	 	 	 	 	 	 	 	 ddZddZddZdd fdZddZddZ	ddZ
d	 Z xZS )r,  a  
    A Job is a wrapper over the Future class that represents a prediction call that has been
    submitted by the Gradio client. This class is not meant to be instantiated directly, but rather
    is created by the Client.submit() method.

    A Job object includes methods to get the status of the prediction call, as well to get the outputs
    of the prediction call. Job objects are also iterable, and can be used in a loop to get the outputs
    of prediction calls as they become available for generator endpoints.
    c                X    || _         || _        d| _        || _        || _        || _        y)a  
        Parameters:
            future: The future object that represents the prediction call, created by the Client.submit() method
            communicator: The communicator object that is used to communicate between the client and the background thread running the job
            verbose: Whether to print any status-related messages to the console
            space_id: The space ID corresponding to the Client object that created this Job object
        r   N)r#  r  _counterrG   rK   r1  )r   r#  r  rG   rK   r  s         r   r   zJob.__init__  s/     ( #r   c                    | S r   r   r   s    r   __iter__zJob.__iter__  s    r   c                   | j                   s
t               	 | j                   j                  5  t        | j                   j                  j
                        | j                  dz   k\  rM| j                   j                  j
                  | j                     }| xj                  dz  c_        |cd d d        S | j                   j                  j                  j                  t        j                  k(  r@| j                  t        | j                   j                  j
                        k\  r
t               t        j                  d       d d d        7# 1 sw Y   xY w)Nr?   gMbP?)r  StopIterationr  r   r2  r  rq  latest_statuscoder   FINISHEDr^   r_   )r   rA  s     r   __next__zJob.__next__  s      /!""'' 
"t((,,4459JJ))--55dmmDAMMQ&M	
" 
" %%))77<<OT->->-B-B-J-J)KK'/)

5!
" 
" 
"s   A=E5BEEc                $    t         |   |      S )a.  
        Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.

        Parameters:
            timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time.
        Returns:
            The result of the call that the future represents. For generator functions, it will return the final iteration.
        Example:
            from gradio_client import Client
            calculator = Client(src="gradio/calculator")
            job = calculator.submit("foo", "add", 4, fn_index=0)
            job.result(timeout=5)
            >> 9
        r   )superr  )r   r   	__class__s     r   r  z
Job.result  s     w~g~..r   c                    | j                   sg S | j                   j                  5  | j                   j                  j                  cddd       S # 1 sw Y   yxY w)a  
        Returns a list containing the latest outputs from the Job.

        If the endpoint has multiple output components, the list will contain
        a tuple of results. Otherwise, it will contain the results without storing them
        in tuples.

        For endpoints that are queued, this list will contain the final job output even
        if that endpoint does not use a generator function.

        Example:
            from gradio_client import Client
            client = Client(src="gradio/count_generator")
            job = client.submit(3, api_name="/count")
            while not job.done():
                time.sleep(0.1)
            job.outputs()
            >> ['0', '1', '2']
        N)r  r  r2  r  r   s    r   r  zJob.outputs  sK    (   I""'' 5((,,445 5 5s    AAc           	        t        j                         }d}| j                  r5| j                  j                  5  | j                  j                  }ddd       |r t        t        j                  ddd|dd      S | j                         rV| j                  j                  s t        t        j                  ddd|dd      S t        t        j                  ddd|dd      S | j                  s t        t        j                  ddd|dd      S | j                  j                  5  | j                  j                  j                  j                  }| j                   r8| j"                  r,|r*|dkD  r%t%        dt'        |       d| j"                   d	       | j                  j                  j                  cddd       S # 1 sw Y   lxY w# 1 sw Y   yxY w)
a<  
        Returns the latest status update from the Job in the form of a StatusUpdate
        object, which contains the following fields: code, rank, queue_size, success, time, eta, and progress_data.

        progress_data is a list of updates emitted by the gr.Progress() tracker of the event handler. Each element
        of the list has the following fields: index, length, unit, progress, desc. If the event handler does not have
        a gr.Progress() tracker, the progress_data field will be None.

        Example:
            from gradio_client import Client
            client = Client(src="gradio/calculator")
            job = client.submit(5, "add", 4, api_name="/predict")
            job.status()
            >> <Status.STARTING: 'STARTING'>
            job.status().eta
            >> 43.241  # seconds
        FNr   )rw  rank
queue_sizesuccessr^   etaprogress_dataT   zIDue to heavy traffic on this app, the prediction will take approximately zn seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(r_  )r   nowr  r  should_cancelr    r   	CANCELLEDr   r#  
_exceptionrx  
PROCESSINGr2  rv  r  rG   rK   r]   rH  )r   r^   	cancelledr  s       r   rn  z
Job.status*  s   $ ||~	""'' < --;;	<%%"  99;;;))## "&  $#!"&  ""&&"  ""'' ;''++99==<<DMMccBhcdghkdlcm n@ AE  AN  AN  @O  OPQ ((,,::; ;Y< <X; ;s   F:"BG:GGc                   | j                   rN| j                   j                  5  d| j                   _        | j                  r| j                          	 ddd       y| j                  j                         S # 1 sw Y   #xY w)a  Cancels the job as best as possible.

        If the app you are connecting to has the gradio queue enabled, the job
        will be cancelled locally as soon as possible. For apps that do not use the
        queue, the job cannot be cancelled if it's been sent to the local executor
        (for the time being).

        Note: In general, this DOES not stop the process from running in the upstream server
        except for the following situations:

        1. If the job is queued upstream, it will be removed from the queue and the server will not run the job
        2. If the job has iterative outputs, the job will finish as soon as the current iteration finishes running
        3. If the job has not been picked up by the queue yet, the queue will not pick up the job
        TN)r  r  r  r1  r#  cancelr   s    r   r  z
Job.cancelt  sm     ""'' 26!!/>>NN$	 
 {{!!## s   /A55A>c                .    t        | j                  |      S )z,Forwards any properties to the Future class.)getattrr#  )r   r  s     r   __getattr__zJob.__getattr__  s    t{{D))r   )NTNN)
r#  r   r  rl  rG   r  rK   r  r  zCallable[[], None] | None)r'  r,  )r'  ztuple | Anyr   )r   zfloat | Noner'  r   )r'  zlist[tuple | Any])r'  r    )r'  r  )r  r  r  r  r   rs  ry  r  r  rn  r  r  __classcell__)r|  s   @r   r,  r,    sp     -1#04$$ *$ 	$
 $ .$,""/"54H;T$.*r   r,  )Ir  
__future__r   concurrent.futuresr   rZ  r   rM  rO   r  r  r`  r  r   r^   urllib.parserg   r   r   collections.abcr   r   dataclassesr   r   	functoolsr   pathlibr	   r
   typingr   r   r   r   r   r   r   huggingface_hub.utilsr   r   r   	packagingr   r0   r   gradio_client.compatibilityr   gradio_client.data_classesr   gradio_client.documentationr   gradio_client.exceptionsr   r   gradio_client.utilsr   r   r   r   r   r   r    environre   rN   r\  rV   r)   r  r  r   r,  r   r   r   <module>r     sS   2 "     	 	         $ % !        I I 
   ? 4 0 B   ::>>"34 				(*9 
 
)Xz;8HIB B JBJ       z
 z
z 
(Ix(C*& C* )C*r   