U
    9%eE                    @   sR  d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z, d d	l-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d d
l6m7Z7m8Z8m9Z9m:Z: er6d dl;Z<d dl=m>Z> e ?e@ZAG dd dZBdS )    N)asdict)	TYPE_CHECKINGAnyDictIterableListLiteralOptionalUnionoverload)	HTTPError)CaseInsensitiveDict)ALL_INFERENCE_API_FRAMEWORKSINFERENCE_ENDPOINTMAIN_INFERENCE_API_FRAMEWORKS)TASKS_EXPECTING_IMAGESContentTInferenceTimeoutErrorModelStatus_b64_encode_b64_to_image_bytes_to_dict_bytes_to_image_bytes_to_list_get_recommended_model_import_numpy_is_tgi_server_open_as_binary_set_as_non_tgi _stream_text_generation_response)TextGenerationParametersTextGenerationRequestTextGenerationResponseTextGenerationStreamResponseraise_text_generation_error)ClassificationOutputConversationalOutputFillMaskOutputImageSegmentationOutputObjectDetectionOutputQuestionAnsweringOutputTableQuestionAnsweringOutputTokenClassificationOutput)BadRequestErrorbuild_hf_headersget_sessionhf_raise_for_status)Imagec                   @   s  e Zd ZdZdlee eeedf ee ee	eef  ee	eef  ddddZ
dd Zedddddd	eeee	ef  ee ee ee ed
 edddZedddddd	eeee	ef  ee ee ee ed ee dddZddddd
d	eeee	ef  ee ee ee eeeee f dddZddeee ee dddZddeee edddZdmdddeeee  eee  ee	eef  ee edddZddeeee ee dddZddeeee ee dddZddeee d d!d"d#Zddeee ee d!d$d%Zddeee ee d&d'd(Zddeee ee  d&d)d*Z!dnddddddd+eee ee ee" ee" ee" ee ee d,d-	d.d/Z#ddeee ed&d0d1Z$doedeed2 ee f e	eee f d3d4d5Z%ddeee ee& d&d6d7Z'ddeeee ed8d9d:Z(ddeee ee ee d;d<d=Z)dddeee	eef  ee ed>d?d@Z*dde	eef eee e+dAdBdCZ,e	eef eee dDdEdFZ-e	eef eee dDdGdHZ.ddeee ee d!dIdJZ/edddd
dKddd
dddddddd
dLeed
 ed
 ee ee"ee" ee eee" eee  ee ee" ee ee" ee eedMdNdOZ0edddd
dKddd
dddddddd
dLeed ed
 ee ee"ee" ee eee" eee  ee ee" ee ee" ee ee1dMdPdOZ0edddd
dKddd
dddddddd
dLeed
 ed ee ee"ee" ee eee" eee  ee ee" ee ee" ee eee dMdQdOZ0edddd
dKddd
dddddddd
dLeed ed ee ee"ee" ee eee" eee  ee ee" ee ee" ee eee2 dMdRdOZ0d
d
dd
dKddd
dddddddd
d
dSeeeee ee"ee" ee eee" eee  ee ee" ee ee" ee eeeee1ee ee2 f dTdUdOZ0ddddddd+eee ee ee ee ee ee d,dVdWdXZ3ddeee ed!dYdZZ4ddeee ee5 d!d[d\Z6ddeee ed!d]d^Z7d
dd_eee eee ee d`dadbZ8ddeee ee ee dcdddeZ9dpee ee edfdgdhZ:dqee e;didjdkZ<dS )rInferenceClientaZ  
    Initialize a new Inference Client.

    [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used
    seamlessly with either the (free) Inference API or self-hosted Inference Endpoints.

    Args:
        model (`str`, `optional`):
            The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `bigcode/starcoder`
            or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
            automatically selected for the task.
        token (`str`, *optional*):
            Hugging Face token. Will default to the locally saved token. Pass `token=False` if you don't want to send
            your token to the server.
        timeout (`float`, `optional`):
            The maximum number of seconds to wait for a response from the server. Loading a new model in Inference
            API can take up to several minutes. Defaults to None, meaning it will loop until the server is available.
        headers (`Dict[str, str]`, `optional`):
            Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
            Values in this dictionary will override the default values.
        cookies (`Dict[str, str]`, `optional`):
            Additional cookies to send to the server.
    N)modeltokentimeoutheaderscookiesreturnc                 C   s:   || _ tt|d| _|d k	r*| j| || _|| _d S )N)r4   )r3   r   r.   r6   updater7   r5   )selfr3   r4   r5   r6   r7    r;   `/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/huggingface_hub/inference/_client.py__init__   s    zInferenceClient.__init__c                 C   s    d| j r| j nd d| j dS )Nz<InferenceClient(model=' z', timeout=z)>)r3   r5   )r:   r;   r;   r<   __repr__   s    zInferenceClient.__repr__.)jsondatar3   taskstreamF)r@   rA   r3   rB   rC   r8   c                C   s   d S Nr;   r:   r@   rA   r3   rB   rC   r;   r;   r<   post   s    
zInferenceClient.postTc                C   s   d S rD   r;   rE   r;   r;   r<   rF      s    
c                C   s  |  ||}|dk	r&|dk	r&td | j }|tkrHd|krHd|d< t }| j}	t|\}
z"t	 j
|||
|| j| j|d}W n2 tk
r } ztd| |W 5 d}~X Y nX W 5 Q R X zt| |r| n|jW S  tk
r } z|jjdkrx|	dk	r4t | |	kr4td| d	| j d
|td|  td |	dk	rpt| jt |  d}	W Y qV W 5 d}~X Y qVX qVdS )a	  
        Make a POST request to the inference server.

        Args:
            json (`Union[str, Dict, List]`, *optional*):
                The JSON data to send in the request body. Defaults to None.
            data (`Union[str, Path, bytes, BinaryIO]`, *optional*):
                The content to send in the request body. It can be raw bytes, a pointer to an opened file, a local file
                path, or a URL to an online resource (image, audio file,...). If both `json` and `data` are passed,
                `data` will take precedence. At least `json` or `data` must be provided. Defaults to None.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. Will override the model defined at the instance level. Defaults to None.
            task (`str`, *optional*):
                The task to perform on the inference. Used only to default to a recommended model if `model` is not
                provided. At least `model` or `task` must be provided. Defaults to None.
            stream (`bool`, *optional*):
                Whether to iterate over streaming APIs.

        Returns:
            bytes: The raw bytes returned by the server.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.
        Nz.Ignoring `json` as `data` is passed as binary.Acceptz	image/png)r@   rA   r6   r7   r5   rC   zInference call timed out: i  z Model not loaded on the server: z/. Please retry with a higher timeout (current: z).z.Waiting for model to be loaded on the server:    )_resolve_urlwarningswarnr6   copyr   timer5   r   r/   rF   r7   TimeoutErrorr   r0   
iter_linescontentr   responsestatus_codeloggerinfosleepmax)r:   r@   rA   r3   rB   rC   urlr6   t0r5   Zdata_as_binaryrQ   errorr;   r;   r<   rF      sL    %



	,

)r3   )audior3   r8   c                C   s   | j ||dd}t|S )a  
        Perform audio classification on the provided audio content.

        Args:
            audio (Union[str, Path, bytes, BinaryIO]):
                The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an
                audio file.
            model (`str`, *optional*):
                The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
                or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
                audio classification will be used.

        Returns:
            `List[Dict]`: The classification output containing the predicted label and its confidence.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.audio_classification("audio.flac")
        [{'score': 0.4976358711719513, 'label': 'hap'}, {'score': 0.3677836060523987, 'label': 'neu'},...]
        ```
        zaudio-classificationrA   r3   rB   rF   r   r:   rZ   r3   rQ   r;   r;   r<   audio_classification   s    #z$InferenceClient.audio_classificationc                C   s   | j ||dd}t|d S )a2  
        Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.

        Args:
            audio (Union[str, Path, bytes, BinaryIO]):
                The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file.
            model (`str`, *optional*):
                The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. If not provided, the default recommended model for ASR will be used.

        Returns:
            str: The transcribed text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.automatic_speech_recognition("hello_world.flac")
        "hello world"
        ```
        zautomatic-speech-recognitionr[   textrF   r   r]   r;   r;   r<   automatic_speech_recognition&  s    !z,InferenceClient.automatic_speech_recognition)
parametersr3   )r_   generated_responsespast_user_inputsrb   r3   r8   c                C   s\   dd|ii}|dk	r ||d d< |dk	r4||d d< |dk	rD||d< | j ||dd}t|S )	a  
        Generate conversational responses based on the given input text (i.e. chat with the API).

        Args:
            text (`str`):
                The last input from the user in the conversation.
            generated_responses (`List[str]`, *optional*):
                A list of strings corresponding to the earlier replies from the model. Defaults to None.
            past_user_inputs (`List[str]`, *optional*):
                A list of strings corresponding to the earlier replies from the user. Should be the same length as
                `generated_responses`. Defaults to None.
            parameters (`Dict[str, Any]`, *optional*):
                Additional parameters for the conversational task. Defaults to None. For more details about the available
                parameters, please refer to [this page](https://huggingface.co/docs/api-inference/detailed_parameters#conversational-task)
            model (`str`, *optional*):
                The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
                Defaults to None.

        Returns:
            `Dict`: The generated conversational output.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> output = client.conversational("Hi, who are you?")
        >>> output
        {'generated_text': 'I am the one who knocks.', 'conversation': {'generated_responses': ['I am the one who knocks.'], 'past_user_inputs': ['Hi, who are you?']}, 'warnings': ['Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.']}
        >>> client.conversational(
        ...     "Wow, that's scary!",
        ...     generated_responses=output["conversation"]["generated_responses"],
        ...     past_user_inputs=output["conversation"]["past_user_inputs"],
        ... )
        ```
        inputsr_   Nrc   rd   rb   conversationalr@   r3   rB   r`   )r:   r_   rc   rd   rb   r3   payloadrQ   r;   r;   r<   rf   J  s    3zInferenceClient.conversational)imagequestionr3   r8   c                C   s&   |t |d}| j||dd}t|S )a  
        Answering open-ended questions based on an image.

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
            question (`str`):
                Question to be answered.
            model (`str`, *optional*):
                The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used.
                Defaults to None.

        Returns:
            `List[Dict]`: a list of dictionaries containing the predicted label and associated probability.

        Raises:
            `InferenceTimeoutError`:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.visual_question_answering(
        ...     image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
        ...     question="What is the animal doing?"
        ... )
        [{'score': 0.778609573841095, 'answer': 'laying down'},{'score': 0.6957435607910156, 'answer': 'sitting'}, ...]
        ```
        rj   ri   zvisual-question-answeringrg   r   rF   r   r:   ri   rj   r3   rh   rQ   r;   r;   r<   visual_question_answering  s    (z)InferenceClient.visual_question_answeringc                C   s&   |t |d}| j||dd}t|S )a  
        Answer questions on document images.

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
            question (`str`):
                Question to be answered.
            model (`str`, *optional*):
                The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used.
                Defaults to None.

        Returns:
            `List[Dict]`: a list of dictionaries containing the predicted label, associated probability, word ids, and page number.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
        [{'score': 0.42515629529953003, 'answer': 'us-001', 'start': 16, 'end': 16}]
        ```
        rk   zdocument-question-answeringrg   rl   rm   r;   r;   r<   document_question_answering  s    %z+InferenceClient.document_question_answeringz
np.ndarray)r_   r3   r8   c                C   s,   | j d|i|dd}t }|jt|ddS )a   
        Generate embeddings for a given text.

        Args:
            text (`str`):
                The text to embed.
            model (`str`, *optional*):
                The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
                Defaults to None.

        Returns:
            `np.ndarray`: The embedding representing the input text as a float32 numpy array.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.feature_extraction("Hi, who are you?")
        array([[ 2.424802  ,  2.93384   ,  1.1750331 , ...,  1.240499, -0.13776633, -0.7889173 ],
        [-0.42943227, -0.6364878 , -1.693462  , ...,  0.41978157, -2.4336355 ,  0.6162071 ],
        ...,
        [ 0.28552425, -0.928395  , -1.2077185 , ...,  0.76810825, -2.1069427 ,  0.6236161 ]], dtype=float32)
        ```
        re   feature-extractionrg   Zfloat32)Zdtype)rF   r   arrayr   )r:   r_   r3   rQ   npr;   r;   r<   feature_extraction  s     z"InferenceClient.feature_extractionc                C   s   | j d|i|dd}t|S )a  
        Fill in a hole with a missing word (token to be precise).

        Args:
            text (`str`):
                a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask).
            model (`str`, *optional*):
                The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used.
                Defaults to None.

        Returns:
            `List[Dict]`: a list of fill mask output dictionaries containing the predicted label, associated
            probability, token reference, and completed text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.fill_mask("The goal of life is <mask>.")
        [{'score': 0.06897063553333282,
        'token': 11098,
        'token_str': ' happiness',
        'sequence': 'The goal of life is happiness.'},
        {'score': 0.06554922461509705,
        'token': 45075,
        'token_str': ' immortality',
        'sequence': 'The goal of life is immortality.'}]
        ```
        re   z	fill-maskrg   r\   r:   r_   r3   rQ   r;   r;   r<   	fill_mask   s    %zInferenceClient.fill_mask)ri   r3   r8   c                C   s   | j ||dd}t|S )a  
        Perform image classification on the given image using the specified model.

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The image to classify. It can be raw bytes, an image file, or a URL to an online image.
            model (`str`, *optional*):
                The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
                deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.

        Returns:
            `List[Dict]`: a list of dictionaries containing the predicted label and associated probability.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
        [{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...]
        ```
        zimage-classificationr[   r\   r:   ri   r3   rQ   r;   r;   r<   image_classification(  s    !z$InferenceClient.image_classificationc                C   sf   | j ||dd}t|}t|tsHtdt| dt|dd  d|D ]}t|d |d< qL|S )	ap  
        Perform image segmentation on the given image using the specified model.

        <Tip warning={true}>

        You must have `PIL` installed if you want to work with images (`pip install Pillow`).

        </Tip>

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The image to segment. It can be raw bytes, an image file, or a URL to an online image.
            model (`str`, *optional*):
                The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
                deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.

        Returns:
            `List[Dict]`: A list of dictionaries containing the segmented masks and associated attributes.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.image_segmentation("cat.jpg"):
        [{'score': 0.989008, 'label': 'LABEL_184', 'mask': <PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>}, ...]
        ```
        zimage-segmentationr[   "Server output must be a list. Got : N   ...mask)rF   r   
isinstancelist
ValueErrortypestrr   )r:   ri   r3   rQ   outputitemr;   r;   r<   image_segmentationL  s    )
&z"InferenceClient.image_segmentation)negative_promptheightwidthnum_inference_stepsguidance_scaler3   r1   )	ri   promptr   r   r   r   r   r3   r8   c                K   s   ||||||d|	}
t dd |
 D r6|}d}n:d}dt|i}|
 D ] \}}|dk	rN||di |< qN| j|||dd}t|S )	a;  
        Perform image-to-image translation using a specified model.

        <Tip warning={true}>

        You must have `PIL` installed if you want to work with images (`pip install Pillow`).

        </Tip>

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The input image for translation. It can be raw bytes, an image file, or a URL to an online image.
            prompt (`str`, *optional*):
                The text prompt to guide the image generation.
            negative_prompt (`str`, *optional*):
                A negative prompt to guide the translation process.
            height (`int`, *optional*):
                The height in pixels of the generated image.
            width (`int`, *optional*):
                The width in pixels of the generated image.
            num_inference_steps (`int`, *optional*):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, *optional*):
                Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `Image`: The translated image.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
        >>> image.save("tiger.jpg")
        ```
        )r   r   r   r   r   r   c                 s   s   | ]}|d kV  qd S rD   r;   ).0Z	parameterr;   r;   r<   	<genexpr>  s     z1InferenceClient.image_to_image.<locals>.<genexpr>Nre   rb   zimage-to-image)r@   rA   r3   rB   )allvaluesr   items
setdefaultrF   r   )r:   ri   r   r   r   r   r   r   r3   kwargsrb   rA   rh   keyvaluerQ   r;   r;   r<   image_to_image  s&    =	zInferenceClient.image_to_imagec                C   s    | j ||dd}t|d d S )a  
        Takes an input image and return text.

        Models can have very different outputs depending on your use case (image captioning, optical character recognition
        (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model's specificities.

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The input image to caption. It can be raw bytes, an image file, or a URL to an online image..
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `str`: The generated text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.image_to_text("cat.jpg")
        'a cat standing in a grassy field '
        >>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
        'a dog laying on the grass next to a flower pot '
        ```
        zimage-to-textr[   r   generated_textr`   rv   r;   r;   r<   image_to_text  s    !zInferenceClient.image_to_textr   )
frameworksr8   c                    s   |dkrt }n|dkrt}nt|tr,|g}tt|}i  ttt dd fdd}|D ]6}t j	t
 d| | jd}t| |||  qZ  D ] \}}tt|dd	 d
 |< q S )a  
        List models currently deployed on the Inference API service.

        This helper checks deployed models framework by framework. By default, it will check the 4 main frameworks that
        are supported and account for 95% of the hosted models. However, if you want a complete list of models you can
        specify `frameworks="all"` as input. Alternatively, if you know before-hand which framework you are interested
        in, you can also restrict to search to this one (e.g. `frameworks="text-generation-inference"`). The more
        frameworks are checked, the more time it will take.

        <Tip>

        This endpoint is mostly useful for discoverability. If you already know which model you want to use and want to
        check its availability, you can directly use [`~InferenceClient.get_model_status`].

        </Tip>

        Args:
            frameworks (`Literal["all"]` or `List[str]` or `str`, *optional*):
                The frameworks to filter on. By default only a subset of the available frameworks are tested. If set to
                "all", all available frameworks will be tested. It is also possible to provide a single framework or a
                custom set of frameworks to check.

        Returns:
            `Dict[str, List[str]]`: A dictionary mapping task names to a sorted list of model IDs.

        Example:
        ```python
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()

        # Discover zero-shot-classification models currently deployed
        >>> models = client.list_deployed_models()
        >>> models["zero-shot-classification"]
        ['Narsil/deberta-large-mnli-zero-cls', 'facebook/bart-large-mnli', ...]

        # List from only 1 framework
        >>> client.list_deployed_models("text-generation-inference")
        {'text-generation': ['bigcode/starcoder', 'meta-llama/Llama-2-70b-chat-hf', ...], ...}
        ```
        Nr   )	frameworkr   r8   c                    s^   |D ]T}| dkr>  dg |d    dg |d  q  |d g |d  qd S )Nzsentence-transformersrp   Zmodel_idsentence-similarityrB   )r   append)r   r   r3   Zmodels_by_taskr;   r<   _unpack_response.  s
    z>InferenceClient.list_deployed_models.<locals>._unpack_responsez/framework/r6   c                 S   s   |   S rD   )lower)xr;   r;   r<   <lambda>?      z6InferenceClient.list_deployed_models.<locals>.<lambda>)r   )r   r   r}   r   r~   setr   r   r/   getr   r6   r0   r@   r   sorted)r:   r   r   r   rQ   rB   modelsr;   r   r<   list_deployed_models  s     ,

z$InferenceClient.list_deployed_modelsc                C   sL   | j ||dd}t|}t|tsHtdt| dt|dd  d|S )a  
        Perform object detection on the given image using the specified model.

        <Tip warning={true}>

        You must have `PIL` installed if you want to work with images (`pip install Pillow`).

        </Tip>

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The image to detect objects on. It can be raw bytes, an image file, or a URL to an online image.
            model (`str`, *optional*):
                The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
                deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.

        Returns:
            `List[ObjectDetectionOutput]`: A list of dictionaries containing the bounding boxes and associated attributes.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.
            `ValueError`:
                If the request output is not a List.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.object_detection("people.jpg"):
        [{"score":0.9486683011054993,"label":"person","box":{"xmin":59,"ymin":39,"xmax":420,"ymax":510}}, ... ]
        ```
        zobject-detectionr[   rx   ry   Nrz   r{   )rF   r   r}   r~   r   r   r   )r:   ri   r3   rQ   r   r;   r;   r<   object_detectionB  s
    *
&z InferenceClient.object_detection)rj   contextr3   r8   c                C   s"   ||d}| j ||dd}t|S )a{  
        Retrieve the answer to a question from a given text.

        Args:
            question (`str`):
                Question to be answered.
            context (`str`):
                The context of the question.
            model (`str`):
                The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint.

        Returns:
            `Dict`: a dictionary of question answering output containing the score, start index, end index, and answer.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
        {'score': 0.9326562285423279, 'start': 11, 'end': 16, 'answer': 'Clara'}
        ```
        )rj   r   zquestion-answeringrg   r`   )r:   rj   r   r3   rh   rQ   r;   r;   r<   question_answeringr  s    !
z"InferenceClient.question_answering)sentenceother_sentencesr3   r8   c                C   s"   | j d||di|dd}t|S )a  
        Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.

        Args:
            sentence (`str`):
                The main sentence to compare to others.
            other_sentences (`List[str]`):
                The list of sentences to compare to.
            model (`str`, *optional*):
                The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
                Defaults to None.

        Returns:
            `List[float]`: The embedding representing the input text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.sentence_similarity(
        ...     "Machine learning is so easy.",
        ...     other_sentences=[
        ...         "Deep learning is so straightforward.",
        ...         "This is so difficult, like rocket science.",
        ...         "I can't believe how much I struggled with this.",
        ...     ],
        ... )
        [0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
        ```
        re   )Zsource_sentenceZ	sentencesr   rg   r\   )r:   r   r   r3   rQ   r;   r;   r<   sentence_similarity  s    (z#InferenceClient.sentence_similarity)r_   rb   r3   r8   c                C   s8   d|i}|dk	r||d< | j ||dd}t|d d S )a  
        Generate a summary of a given text using a specified model.

        Args:
            text (`str`):
                The input text to summarize.
            parameters (`Dict[str, Any]`, *optional*):
                Additional parameters for summarization. Check out this [page](https://huggingface.co/docs/api-inference/detailed_parameters#summarization-task)
                for more details.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `str`: The generated summary text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.summarization("The Eiffel tower...")
        'The Eiffel tower is one of the most famous landmarks in the world....'
        ```
        re   Nrb   summarizationrg   r   Zsummary_textr`   )r:   r_   rb   r3   rh   rQ   r;   r;   r<   r     s
    %zInferenceClient.summarization)tablequeryr3   r8   c                C   s   | j ||d|dd}t|S )a  
        Retrieve the answer to a question from information given in a table.

        Args:
            table (`str`):
                A table of data represented as a dict of lists where entries are headers and the lists are all the
                values, all lists must have the same size.
            query (`str`):
                The query in plain text that you want to ask the table.
            model (`str`):
                The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face
                Hub or a URL to a deployed Inference Endpoint.

        Returns:
            `Dict`: a dictionary of table question answering output containing the answer, coordinates, cells and the aggregator used.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> query = "How many stars does the transformers repository have?"
        >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
        >>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
        {'answer': 'AVERAGE > 36542', 'coordinates': [[0, 1]], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
        ```
        )r   r   ztable-question-answeringrg   r`   )r:   r   r   r3   rQ   r;   r;   r<   table_question_answering  s    #z(InferenceClient.table_question_answering)r   r3   r8   c                C   s   | j d|i|dd}t|S )aU  
        Classifying a target category (a group) based on a set of attributes.

        Args:
            table (`Dict[str, Any]`):
                Set of attributes to classify.
            model (`str`):
                The model to use for the tabular-classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint.

        Returns:
            `List`: a list of labels, one per row in the initial table.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> table = {
        ...     "fixed_acidity": ["7.4", "7.8", "10.3"],
        ...     "volatile_acidity": ["0.7", "0.88", "0.32"],
        ...     "citric_acid": ["0", "0", "0.45"],
        ...     "residual_sugar": ["1.9", "2.6", "6.4"],
        ...     "chlorides": ["0.076", "0.098", "0.073"],
        ...     "free_sulfur_dioxide": ["11", "25", "5"],
        ...     "total_sulfur_dioxide": ["34", "67", "13"],
        ...     "density": ["0.9978", "0.9968", "0.9976"],
        ...     "pH": ["3.51", "3.2", "3.23"],
        ...     "sulphates": ["0.56", "0.68", "0.82"],
        ...     "alcohol": ["9.4", "9.8", "12.6"],
        ... }
        >>> client.tabular_classification(table=table, model="julien-c/wine-quality")
        ["5", "5", "5"]
        ```
        r   ztabular-classificationrg   r\   r:   r   r3   rQ   r;   r;   r<   tabular_classification"  s    )z&InferenceClient.tabular_classificationc                C   s   | j d|i|dd}t|S )a  
        Predicting a numerical target value given a set of attributes/features in a table.

        Args:
            table (`Dict[str, Any]`):
                Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical.
            model (`str`):
                The model to use for the tabular-regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint.

        Returns:
            `List`: a list of predicted numerical target values.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> table = {
        ...     "Height": ["11.52", "12.48", "12.3778"],
        ...     "Length1": ["23.2", "24", "23.9"],
        ...     "Length2": ["25.4", "26.3", "26.5"],
        ...     "Length3": ["30", "31.2", "31.1"],
        ...     "Species": ["Bream", "Bream", "Bream"],
        ...     "Width": ["4.02", "4.3056", "4.6961"],
        ... }
        >>> client.tabular_regression(table, model="scikit-learn/Fish-Weight")
        [110, 120, 130]
        ```
        r   ztabular-regressionrg   r\   r   r;   r;   r<   tabular_regressionN  s    $z"InferenceClient.tabular_regressionc                C   s    | j d|i|dd}t|d S )a  
        Perform text classification (e.g. sentiment-analysis) on the given text.

        Args:
            text (`str`):
                A string to be classified.
            model (`str`, *optional*):
                The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used.
                Defaults to None.

        Returns:
            `List[Dict]`: a list of dictionaries containing the predicted label and associated probability.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.text_classification("I like you")
        [{'label': 'POSITIVE', 'score': 0.9998695850372314}, {'label': 'NEGATIVE', 'score': 0.0001304351753788069}]
        ```
        re   ztext-classificationrg   r   r\   rt   r;   r;   r<   text_classificationu  s    z#InferenceClient.text_classification   )detailsrC   r3   	do_samplemax_new_tokensbest_ofrepetition_penaltyreturn_full_textseedstop_sequencestemperaturetop_ktop_ptruncate	typical_p	watermark)r   r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   r8   c                C   s   d S rD   r;   r:   r   r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   r;   r;   r<   text_generation  s    zInferenceClient.text_generationc                C   s   d S rD   r;   r   r;   r;   r<   r     s    c                C   s   d S rD   r;   r   r;   r;   r<   r     s    c                C   s   d S rD   r;   r   r;   r;   r<   r     s    )r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   decoder_input_details)r   r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r8   c                C   s  |r|st d d}t||||||	|
|dk	r2|ng |||||||d}t|||d}t|}t|sg }dD ](}|d | dk	r|| |d |= qnt|dkrt d	| d
t |rt dt d}|rt	dz| j
||d|d}W n tk
rr } zdt|trZdt|krZt| | j|||||||||	|
||||||||d W Y S t| W 5 d}~X Y nX |rt||S t|d }|rtf |S |d S )a"  
        Given a prompt, generate the following text.

        It is recommended to have Pydantic installed in order to get inputs validated. This is preferable as it allow
        early failures.

        API endpoint is supposed to run with the `text-generation-inference` backend (TGI). This backend is the
        go-to solution to run large language models at scale. However, for some smaller models (e.g. "gpt2") the
        default `transformers` + `api-inference` solution is still in use. Both approaches have very similar APIs, but
        not exactly the same. This method is compatible with both approaches but some parameters are only available for
        `text-generation-inference`. If some parameters are ignored, a warning message is triggered but the process
        continues correctly.

        To learn more about the TGI project, please refer to https://github.com/huggingface/text-generation-inference.

        Args:
            prompt (`str`):
                Input text.
            details (`bool`, *optional*):
                By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens,
                probabilities, seed, finish reason, etc.). Only available for models running on with the
                `text-generation-inference` backend.
            stream (`bool`, *optional*):
                By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of
                tokens to be returned. Only available for models running on with the `text-generation-inference`
                backend.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
            do_sample (`bool`):
                Activate logits sampling
            max_new_tokens (`int`):
                Maximum number of generated tokens
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
            repetition_penalty (`float`):
                The parameter for repetition penalty. 1.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
            return_full_text (`bool`):
                Whether to prepend the prompt to the generated text
            seed (`int`):
                Random sampling seed
            stop_sequences (`List[str]`):
                Stop generating tokens if a member of `stop_sequences` is generated
            temperature (`float`):
                The value used to module the logits distribution.
            top_k (`int`):
                The number of highest probability vocabulary tokens to keep for top-k-filtering.
            top_p (`float`):
                If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
                higher are kept for generation.
            truncate (`int`):
                Truncate inputs tokens to the given size
            typical_p (`float`):
                Typical Decoding mass
                See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
            watermark (`bool`):
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken
                into account. Defaults to `False`.

        Returns:
            `Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]`:
            Generated text returned from the server:
            - if `stream=False` and `details=False`, the generated text is returned as a `str` (default)
            - if `stream=True` and `details=False`, the generated text is returned token by token as a `Iterable[str]`
            - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.inference._text_generation.TextGenerationResponse`]
            - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.inference._text_generation.TextGenerationStreamResponse`]

        Raises:
            `ValidationError`:
                If input values are not valid. No HTTP call is made to the server.
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()

        # Case 1: generate text
        >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
        '100% open source and built to be easy to use.'

        # Case 2: iterate over the generated tokens. Useful for large generation.
        >>> for token in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
        ...     print(token)
        100
        %
        open
        source
        and
        built
        to
        be
        easy
        to
        use
        .

        # Case 3: get more details about the generation process.
        >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
        TextGenerationResponse(
            generated_text='100% open source and built to be easy to use.',
            details=Details(
                finish_reason=<FinishReason.Length: 'length'>,
                generated_tokens=12,
                seed=None,
                prefill=[
                    InputToken(id=487, text='The', logprob=None),
                    InputToken(id=53789, text=' hugging', logprob=-13.171875),
                    (...)
                    InputToken(id=204, text=' ', logprob=-7.0390625)
                ],
                tokens=[
                    Token(id=1425, text='100', logprob=-1.0175781, special=False),
                    Token(id=16, text='%', logprob=-0.0463562, special=False),
                    (...)
                    Token(id=25, text='.', logprob=-0.5703125, special=False)
                ],
                best_of_sequences=None
            )
        )

        # Case 4: iterate over the generated tokens with more details.
        # Last object is more complete, containing the full generated text and the finish reason.
        >>> for details in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
        ...     print(details)
        ...
        TextGenerationStreamResponse(token=Token(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
        TextGenerationStreamResponse(token=Token(
            id=25,
            text='.',
            logprob=-0.5703125,
            special=False),
            generated_text='100% open source and built to be easy to use.',
            details=StreamDetails(finish_reason=<FinishReason.Length: 'length'>, generated_tokens=12, seed=None)
        )
        ```
        z`decoder_input_details=True` has been passed to the server but `details=False` is set meaning that the output from the server will be truncated.FN)r   r   r   r   r   r   r   stopr   r   r   r   r   r   r   )re   rC   rb   )r   r   r   r   rb   r   zRAPI endpoint/model for text-generation is not served via TGI. Ignoring parameters .zAPI endpoint/model for text-generation is not served via TGI. Parameter `details=True` will be ignored meaning only the generated text will be returned.zAPI endpoint/model for text-generation is not served via TGI. Cannot return output as a stream. Please pass `stream=False` as input.ztext-generation)r@   r3   rB   rC   z6The following `model_kwargs` are not used by the model)r   r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rJ   rK   r    r!   r   r   r   lenUserWarningr   rF   r   r}   r-   r   r   r   r$   r   r   r"   )r:   r   r   rC   r3   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   requestrh   Zignored_parametersr   Zbytes_outputerA   r;   r;   r<   r     s     3


)r   r   r   r   r   r   r3   r8   c                K   s^   d|i}	|||||d|}
|
  D ] \}}|dk	r$||	di |< q$| j|	|dd}t|S )a  
        Generate an image based on a given text using a specified model.

        <Tip warning={true}>

        You must have `PIL` installed if you want to work with images (`pip install Pillow`).

        </Tip>

        Args:
            prompt (`str`):
                The prompt to generate an image from.
            negative_prompt (`str`, *optional*):
                An optional negative prompt for the image generation.
            height (`float`, *optional*):
                The height in pixels of the image to generate.
            width (`float`, *optional*):
                The width in pixels of the image to generate.
            num_inference_steps (`int`, *optional*):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, *optional*):
                Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `Image`: The generated image.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()

        >>> image = client.text_to_image("An astronaut riding a horse on the moon.")
        >>> image.save("astronaut.png")

        >>> image = client.text_to_image(
        ...     "An astronaut riding a horse on the moon.",
        ...     negative_prompt="low resolution, blurry",
        ...     model="stabilityai/stable-diffusion-2-1",
        ... )
        >>> image.save("better_astronaut.png")
        ```
        re   )r   r   r   r   r   Nrb   ztext-to-imagerg   )r   r   rF   r   )r:   r   r   r   r   r   r   r3   r   rh   rb   r   r   rQ   r;   r;   r<   text_to_image   s    AzInferenceClient.text_to_imagec                C   s   | j d|i|ddS )a   
        Synthesize an audio of a voice pronouncing a given text.

        Args:
            text (`str`):
                The text to synthesize.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `bytes`: The generated audio.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from pathlib import Path
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()

        >>> audio = client.text_to_speech("Hello world")
        >>> Path("hello_world.flac").write_bytes(audio)
        ```
        re   ztext-to-speechrg   )rF   )r:   r_   r3   r;   r;   r<   text_to_speechP  s    zInferenceClient.text_to_speechc                C   s    d|i}| j ||dd}t|S )a  
        Perform token classification on the given text.
        Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text.

        Args:
            text (`str`):
                A string to be classified.
            model (`str`, *optional*):
                The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used.
                Defaults to None.

        Returns:
            `List[Dict]`: List of token classification outputs containing the entity group, confidence score, word, start and end index.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
        [{'entity_group': 'PER',
        'score': 0.9971321225166321,
        'word': 'Sarah Jessica Parker',
        'start': 11,
        'end': 31},
        {'entity_group': 'PER',
        'score': 0.9773476123809814,
        'word': 'Jessica',
        'start': 52,
        'end': 59}]
        ```
        re   ztoken-classificationrg   r\   )r:   r_   r3   rh   rQ   r;   r;   r<   token_classificationp  s    'z$InferenceClient.token_classificationc                C   s$   | j d|i|dd}t|d d S )u  
        Convert text from one language to another.

        Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for
        your specific use case. Source and target languages usually depends on the model.

        Args:
            text (`str`):
                A string to be translated.
            model (`str`, *optional*):
                The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to
                a deployed Inference Endpoint. If not provided, the default recommended translation model will be used.
                Defaults to None.

        Returns:
            `str`: The generated translated text.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.translation("My name is Wolfgang and I live in Berlin")
        'Mein Name ist Wolfgang und ich lebe in Berlin.'
        >>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
        "Je m'appelle Wolfgang et je vis à Berlin."
        ```
        re   translationrg   r   Ztranslation_textr`   rt   r;   r;   r<   r     s    "zInferenceClient.translation)multi_labelr3   )r_   labelsr   r3   r8   c                C   sZ   t |dk rtd| j|d||dd|dd}t|}dd	 t|d
 |d D S )a	  
        Provide as input a text and a set of candidate labels to classify the input text.

        Args:
            text (`str`):
                The input text to classify.
            labels (`List[str]`):
                List of string possible labels. There must be at least 2 labels.
            multi_label (`bool`):
                Boolean that is set to True if classes can overlap.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `List[Dict]`: List of classification outputs containing the predicted labels and their confidence.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> text = (
        ...     "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
        ...     "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
        ...     " mysteries when he went for a run up a hill in Nice, France."
        ... )
        >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
        >>> client.zero_shot_classification(text, labels)
        [
            {"label": "scientific discovery", "score": 0.7961668968200684},
            {"label": "space & cosmos", "score": 0.18570658564567566},
            {"label": "microbiology", "score": 0.00730885099619627},
            {"label": "archeology", "score": 0.006258360575884581},
            {"label": "robots", "score": 0.004559356719255447},
        ]
        >>> client.zero_shot_classification(text, labels, multi_label=True)
        [
            {"label": "scientific discovery", "score": 0.9829297661781311},
            {"label": "space & cosmos", "score": 0.755190908908844},
            {"label": "microbiology", "score": 0.0005462635890580714},
            {"label": "archeology", "score": 0.00047131875180639327},
            {"label": "robots", "score": 0.00030448526376858354},
        ]
        ```
           /You must specify at least 2 classes to compare.,)candidate_labelsr   )re   rb   zzero-shot-classificationrg   c                 S   s   g | ]\}}||d qS ))labelscorer;   )r   r   r   r;   r;   r<   
<listcomp>
  s     z<InferenceClient.zero_shot_classification.<locals>.<listcomp>r   Zscores)r   r   rF   joinr   zip)r:   r_   r   r   r3   rQ   r   r;   r;   r<   zero_shot_classification  s    7z(InferenceClient.zero_shot_classification)ri   r   r3   r8   c                C   s@   t |dk rtd| jt|dd|id|dd}t|S )a  
        Provide input image and text labels to predict text labels for the image.

        Args:
            image (`Union[str, Path, bytes, BinaryIO]`):
                The input image to caption. It can be raw bytes, an image file, or a URL to an online image.
            labels (`List[str]`):
                List of string possible labels. There must be at least 2 labels.
            model (`str`, *optional*):
                The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
                Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.

        Returns:
            `List[Dict]`: List of classification outputs containing the predicted labels and their confidence.

        Raises:
            [`InferenceTimeoutError`]:
                If the model is unavailable or the request times out.
            `HTTPError`:
                If the request fails with an HTTP error status code other than HTTP 503.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()

        >>> client.zero_shot_image_classification(
        ...     "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
        ...     labels=["dog", "cat", "horse"],
        ... )
        [{"label": "dog", "score": 0.956}, ...]
        ```
        r   r   r   r   )ri   rb   zzero-shot-image-classificationrg   )r   r   rF   r   r   r   )r:   ri   r   r3   rQ   r;   r;   r<   zero_shot_image_classification  s    %z.InferenceClient.zero_shot_image_classification)r3   rB   r8   c                 C   st   |p| j }|d k	r*|ds&|dr*|S |d krJ|d krBtdt|}|dkrft d| d| S t d| S )Nzhttp://https://zYou must specify at least a model (repo_id or URL) or a task, either when instantiating `InferenceClient` or when making a request.)rp   r   z
/pipeline//z/models/)r3   
startswithr   r   r   )r:   r3   rB   r;   r;   r<   rI   ;  s    
zInferenceClient._resolve_url)r3   r8   c                 C   s   |p| j }|dkrtd|dr,tdt d| }t j|| jd}t| |	 }d|krpt|d t
|d |d	 |d
 |d dS )a  
        Get the status of a model hosted on the Inference API.

        <Tip>

        This endpoint is mostly useful when you already know which model you want to use and want to check its
        availability. If you want to discover already deployed models, you should rather use [`~InferenceClient.list_deployed_models`].

        </Tip>

        Args:
            model (`str`, *optional*):
                Identifier of the model for witch the status gonna be checked. If model is not provided,
                the model associated with this instance of [`InferenceClient`] will be used. Only InferenceAPI service can be checked so the
                identifier cannot be a URL.


        Returns:
            [`ModelStatus`]: An instance of ModelStatus dataclass, containing information,
                         about the state of the model: load, state, compute type and framework.

        Example:
        ```py
        >>> from huggingface_hub import InferenceClient
        >>> client = InferenceClient()
        >>> client.get_model_status("bigcode/starcoder")
        ModelStatus(loaded=True, state='Loaded', compute_type='gpu', framework='text-generation-inference')
        ```
        NzModel id not provided.r   z;Model status is only available for Inference API endpoints.z/status/r   rY   loadedstatecompute_typer   )r   r   r   r   )r3   r   r   NotImplementedErrorr   r/   r   r6   r0   r@   r   )r:   r3   rW   rQ   Zresponse_datar;   r;   r<   get_model_statusT  s"    

z InferenceClient.get_model_status)NNNNN)NN)N)N)NN)N)=__name__
__module____qualname____doc__r	   r   r
   boolfloatr   r=   r?   r   r   r   r   bytesrF   r   r%   r^   ra   r   r&   rf   rn   r*   ro   rs   r'   ru   rw   r(   r   intr   r   r   r)   r   r   r   r   r+   r   r   r   r   r   r"   r#   r   r   r,   r   r   r   r   rI   r   r   r;   r;   r;   r<   r2   i   s       X*'  

B1)$ ,(6 T% O1  *  3,
  -,'  




  P  /&    I  /r2   )CloggingrM   rJ   dataclassesr   typingr   r   r   r   r   r   r	   r
   r   requestsr   Zrequests.structuresr   Zhuggingface_hub.constantsr   r   r   Z!huggingface_hub.inference._commonr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z*huggingface_hub.inference._text_generationr    r!   r"   r#   r$   Z huggingface_hub.inference._typesr%   r&   r'   r(   r)   r*   r+   r,   Zhuggingface_hub.utilsr-   r.   r/   r0   numpyrr   ZPILr1   	getLoggerr   rS   r2   r;   r;   r;   r<   <module>$   s    ,D(

