o
    htC                     @   s   d dl Z d dlmZmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZ d dlmZmZ ddlmZ dd	lmZ dd
lmZmZmZ erJddlmZ eeZG dd deeZG dd deeZeG dd dZdS )    N)	dataclassfield)datetime)Enum)TYPE_CHECKINGDictOptionalUnion)InferenceEndpointErrorInferenceEndpointTimeoutError   )InferenceClient)AsyncInferenceClient)get_sessionloggingparse_datetimeHfApic                   @   s,   e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
InferenceEndpointStatuspendinginitializingupdatingupdateFailedrunningpausedfailedscaledToZeroN)__name__
__module____qualname__PENDINGINITIALIZINGUPDATINGUPDATE_FAILEDRUNNINGPAUSEDFAILEDSCALED_TO_ZERO r(   r(   x/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.pyr      s    r   c                   @   s   e Zd ZdZdZdZdS )InferenceEndpointTypepublic	protectedprivateN)r   r   r   PUBlIC	PROTECTEDPRIVATEr(   r(   r(   r)   r*       s    r*   c                   @   sx  e Zd ZU dZeddZeed< eed< eddZeed< eddZ	e
ed< eddZee ed< eddd	Zeed
< eddd	Zeed< eddd	Zeed< eddd	Zeed< eddd	Zeed< eddd	Zeed< eddZeed< edddZeeedf ed< edddZded< e	d@dededeeedf ded dd f
ddZdAddZedefddZ ede!fd d!Z"dBd#ee# d$e#dd fd%d&Z$dCd'd(Z%ddddddddddddd)d*ee d+ee d,ee d-ee# d.ee# d/ee# dee d
ee dee dee d0ee d1eeeef  dd fd2d3Z&dCd4d5Z'dDd7edd fd8d9Z(dCd:d;Z)dAd<d=Z*dAd>d?Z+dS )EInferenceEndpointa  
    Contains information about a deployed Inference Endpoint.

    Args:
        name (`str`):
            The unique name of the Inference Endpoint.
        namespace (`str`):
            The namespace where the Inference Endpoint is located.
        repository (`str`):
            The name of the model repository deployed on this Inference Endpoint.
        status ([`InferenceEndpointStatus`]):
            The current status of the Inference Endpoint.
        url (`str`, *optional*):
            The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
        framework (`str`):
            The machine learning framework used for the model.
        revision (`str`):
            The specific model revision deployed on the Inference Endpoint.
        task (`str`):
            The task associated with the deployed model.
        created_at (`datetime.datetime`):
            The timestamp when the Inference Endpoint was created.
        updated_at (`datetime.datetime`):
            The timestamp of the last update of the Inference Endpoint.
        type ([`InferenceEndpointType`]):
            The type of the Inference Endpoint (public, protected, private).
        raw (`Dict`):
            The raw dictionary data returned from the API.
        token (`str` or `bool`, *optional*):
            Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
            locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.

    Example:
        ```python
        >>> from huggingface_hub import get_inference_endpoint
        >>> endpoint = get_inference_endpoint("my-text-to-image")
        >>> endpoint
        InferenceEndpoint(name='my-text-to-image', ...)

        # Get status
        >>> endpoint.status
        'running'
        >>> endpoint.url
        'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'

        # Run inference
        >>> endpoint.client.text_to_image(...)

        # Pause endpoint to save $$$
        >>> endpoint.pause()

        # ...
        # Resume and wait for deployment
        >>> endpoint.resume()
        >>> endpoint.wait()
        >>> endpoint.client.text_to_image(...)
        ```
    F)initname	namespace
repositorystatusurl)reprr2   	frameworkrevisiontask
created_at
updated_attype)r8   raw)r8   compareN_tokenr   _apitokenapireturnc                 C   s8   |du rddl m} | }|du r|j}| ||||dS )z&Initialize object from raw dictionary.Nr   r   )r?   r4   rA   rB   )hf_apir   rC   )clsr?   r4   rC   rD   r   r(   r(   r)   from_rawy   s   zInferenceEndpoint.from_rawc                 C   s   |    dS )z$Populate fields from raw dictionary.N)_populate_from_rawselfr(   r(   r)   __post_init__   s   zInferenceEndpoint.__post_init__c                 C   "   | j du r	tdt| j | jdS )a  Returns a client to make predictions on this Inference Endpoint.

        Returns:
            [`InferenceClient`]: an inference client pointing to the deployed endpoint.

        Raises:
            [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
        NCannot create a client for this Inference Endpoint as it is not yet deployed. Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again.modelrC   )r7   r
   r   rA   rJ   r(   r(   r)   client      

zInferenceEndpoint.clientc                 C   rM   )a3  Returns a client to make predictions on this Inference Endpoint.

        Returns:
            [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.

        Raises:
            [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
        NrN   rO   )r7   r
   r   rA   rJ   r(   r(   r)   async_client   rR   zInferenceEndpoint.async_client   timeoutrefresh_everyc                 C   s  |dur|dk rt d|dkrt dt }	 | jtjkr(td| j d| jtjkr7td| j d| jtjkr]| j	dur]t
 j| j	| jj| jd	d
}|jdkr]td | S |durmt | |krmtdtd| j d| d t| |   q)a+  Wait for the Inference Endpoint to be deployed.

        Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
        seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
        data.

        Args:
            timeout (`int`, *optional*):
                The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
                indefinitely.
            refresh_every (`int`, *optional*):
                The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.

        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.

        Raises:
            [`InferenceEndpointError`]
                If the Inference Endpoint ended up in a failed state.
            [`InferenceEndpointTimeoutError`]
                If the Inference Endpoint is not deployed after `timeout` seconds.
        Nr   z`timeout` cannot be negative.z!`refresh_every` must be positive.TzInference Endpoint z> failed to deploy. Please check the logs for more information.z> failed to update. Please check the logs for more information.)rC   )headers   z'Inference Endpoint is ready to be used.z<Timeout while waiting for Inference Endpoint to be deployed.z(Inference Endpoint is not deployed yet (z). Waiting zs...)
ValueErrortimer6   r   r&   r
   r3   r#   r$   r7   r   getrB   _build_hf_headersrA   status_codeloggerinfor   sleepfetch)rK   rU   rV   startresponser(   r(   r)   wait   s4   


zInferenceEndpoint.waitc                 C   ,   | j j| j| j| jd}|j| _|   | S )zFetch latest information about the Inference Endpoint.

        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
        r3   r4   rC   )rB   get_inference_endpointr3   r4   rA   r?   rI   rK   objr(   r(   r)   ra      s   zInferenceEndpoint.fetch)acceleratorinstance_sizeinstance_typemin_replicamax_replicascale_to_zero_timeoutr5   r9   r:   r;   custom_imagesecretsrj   rk   rl   rm   rn   ro   rp   rq   c                C   sD   | j j| j| j|||||||||	|
||| jd}|j| _|   | S )a	  Update the Inference Endpoint.

        This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
        optional but at least one must be provided.

        This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
        latest data from the server.

        Args:
            accelerator (`str`, *optional*):
                The hardware accelerator to be used for inference (e.g. `"cpu"`).
            instance_size (`str`, *optional*):
                The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
            instance_type (`str`, *optional*):
                The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
            min_replica (`int`, *optional*):
                The minimum number of replicas (instances) to keep running for the Inference Endpoint.
            max_replica (`int`, *optional*):
                The maximum number of replicas (instances) to scale to for the Inference Endpoint.
            scale_to_zero_timeout (`int`, *optional*):
                The duration in minutes before an inactive endpoint is scaled to zero.

            repository (`str`, *optional*):
                The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
            framework (`str`, *optional*):
                The machine learning framework used for the model (e.g. `"custom"`).
            revision (`str`, *optional*):
                The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
            task (`str`, *optional*):
                The task on which to deploy the model (e.g. `"text-classification"`).
            custom_image (`Dict`, *optional*):
                A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
                Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
            secrets (`Dict[str, str]`, *optional*):
                Secret values to inject in the container environment.
        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
        )r3   r4   rj   rk   rl   rm   rn   ro   r5   r9   r:   r;   rp   rq   rC   )rB   update_inference_endpointr3   r4   rA   r?   rI   )rK   rj   rk   rl   rm   rn   ro   r5   r9   r:   r;   rp   rq   ri   r(   r(   r)   update   s(   9zInferenceEndpoint.updatec                 C   re   )ao  Pause the Inference Endpoint.

        A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
        This is different than scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
        would be automatically restarted when a request is made to it.

        This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
        latest data from the server.

        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
        rf   )rB   pause_inference_endpointr3   r4   rA   r?   rI   rh   r(   r(   r)   pauseC     zInferenceEndpoint.pauseT
running_okc                 C   s.   | j j| j| j|| jd}|j| _|   | S )a  Resume the Inference Endpoint.

        This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
        latest data from the server.

        Args:
            running_ok (`bool`, *optional*):
                If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
                `True`.

        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
        )r3   r4   rw   rC   )rB   resume_inference_endpointr3   r4   rA   r?   rI   )rK   rw   ri   r(   r(   r)   resumeU  s   zInferenceEndpoint.resumec                 C   re   )az  Scale Inference Endpoint to zero.

        An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
        cold start delay. This is different than pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
        would require a manual resume with [`InferenceEndpoint.resume`].

        This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
        latest data from the server.

        Returns:
            [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
        rf   )rB    scale_to_zero_inference_endpointr3   r4   rA   r?   rI   rh   r(   r(   r)   scale_to_zeroj  rv   zInferenceEndpoint.scale_to_zeroc                 C   s   | j j| j| j| jd dS )aT  Delete the Inference Endpoint.

        This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
        to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].

        This is an alias for [`HfApi.delete_inference_endpoint`].
        rf   N)rB   delete_inference_endpointr3   r4   rA   rJ   r(   r(   r)   delete|  s   zInferenceEndpoint.deletec                 C   s   | j d | _| j d d | _| j d d | _| j d d| _| j d d | _| j d d | _| j d d	 | _t	| j d d
 | _
t	| j d d | _| j d | _dS )z}Populate fields from raw dictionary.

        Called in __post_init__ + each time the Inference Endpoint is updated.
        r3   rP   r5   r6   stater7   r9   r:   r;   	createdAt	updatedAtr>   N)r?   r3   r5   r6   r[   r7   r9   r:   r;   r   r<   r=   r>   rJ   r(   r(   r)   rI     s   z$InferenceEndpoint._populate_from_raw)NN)rE   N)NrT   )rE   r1   )T),r   r   r   __doc__r   r3   str__annotations__r5   r6   r   r7   r   r9   r:   r;   r<   r   r=   r>   r*   r?   r   rA   r	   boolrB   classmethodrH   rL   propertyr   rQ   r   rS   intrd   ra   rs   ru   ry   r{   r}   rI   r(   r(   r(   r)   r1   &   s   
 <

4	

P


r1   ) rZ   dataclassesr   r   r   enumr   typingr   r   r   r	   huggingface_hub.errorsr
   r   inference._clientr   "inference._generated._async_clientr   utilsr   r   r   rF   r   
get_loggerr   r^   r   r   r*   r1   r(   r(   r(   r)   <module>   s     
