o
    h=                  	   @   s  U d 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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 ddlmZmZmZmZmZmZ dd	l m!Z!m"Z"m#Z#m$Z$ d
dl%m&Z&m'Z' eryddl(m)Z)m*Z* ddl+m,Z, e-Z.ee-e	f Z/ee0ee/e.de1e2f Z3ddhZ4e5e6Z7eG dd dZ8G dd de0Z9dd Z:dd Z;dd Z<ede3de9fddZ=eded ded fddZ=dee3 dee9 fd dZ=de3de-fd!d"Z>de3d#e-de-fd$d%Z?d&e-ddfd'd(Z@de0defd)d*ZAde0defd+d,ZBde0ddfd-d.ZCd/ee0ef defd0d1ZDd2ee0 d3eEdeee- ee' f fd4d5ZFd2ee0 d3eEdeee- ee' f fd6d7ZGd8e0d3eEdeee-e'f  fd9d:ZHd;ee0 dee& fd<d=ZId;ee0 dee& fd>d?ZJd8e0dee& fd@dAZKdBdCd/dDdee0 fdEdFZLi ZMeee- ee- f eNdG< dHee- dIee- ddfdJdKZOdHee- dee- fdLdMZPdNedefdOdPZQdQee- dRee- defdSdTZRdS )UzEContains utilities used by both the sync and async inference clients.    N)	dataclass)Path)TYPE_CHECKINGAnyAsyncIterableBinaryIODictIterableListLiteralNoReturnOptionalUnionoverload)	HTTPError)GenerationErrorIncompleteGenerationErrorOverloadedErrorTextGenerationErrorUnknownErrorValidationError   )get_sessionis_aiohttp_availableis_numpy_availableis_pillow_available   )ChatCompletionStreamOutputTextGenerationStreamOutput)ClientResponseClientSessionImager"   ztext-to-imagezimage-to-imagec                   @   s\   e Zd ZU eed< eed< ee ed< eeeeef  ed< ee	 ed< eee
f ed< dS )RequestParametersurltaskmodeljsondataheadersN)__name__
__module____qualname__str__annotations__r   r   r   r
   bytesr    r0   r0   W/var/www/html/ai/venv/lib/python3.10/site-packages/huggingface_hub/inference/_common.pyr#   E   s   
 r#   c                       s>   e Zd ZU dZee ed< ddedee f fddZ  Z	S )	MimeBytesa&  
    A bytes object with a mime type.
    To be returned by `_prepare_payload_open_as_mime_bytes` in subclasses.

    Example:
    ```python
        >>> b = MimeBytes(b"hello", "text/plain")
        >>> isinstance(b, bytes)
        True
        >>> b.mime_type
        'text/plain'
    ```
    	mime_typeNr(   c                    s2   t  | |}||_t|tr|d u r|j|_|S N)super__new__r3   
isinstancer2   )clsr(   r3   obj	__class__r0   r1   r6   `   s
   zMimeBytes.__new__r4   )
r*   r+   r,   __doc__r   r-   r.   r/   r6   __classcell__r0   r0   r:   r1   r2   O   s   
 $r2   c                  C   s   t  stddd l} | S )NzMPlease install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).r   )r   ImportErroraiohttp)r?   r0   r0   r1   _import_aiohttpk      r@   c                  C   s   t  stdddl} | S )z.Make sure `numpy` is installed on the machine.zGPlease install numpy to use deal with embeddings (`pip install numpy`).r   N)r   r>   numpy)rB   r0   r0   r1   _import_numpyt   rA   rC   c                  C   s   t  stdddlm}  | S )z,Make sure `PIL` is installed on the machine.zPlease install Pillow to use deal with images (`pip install Pillow`). If you don't want the image to be post-processed, use `client.post(...)` and get the raw response from the server.r   r!   )r   r>   PILr"   r!   r0   r0   r1   _import_pil_image}   s   rE   contentreturnc                 C      d S r4   r0   rF   r0   r0   r1   _open_as_mime_bytes      rJ   c                 C   rH   r4   r0   rI   r0   r0   r1   rJ      rK   c                 C   s  | du rdS t | trt| S t | ttfrtt| S t| drHtd |  }t| dr7t	
| jd nd}t |trBtdt||dS t | tr| dsW| d	r}td
|   t | }|jd}|du rvt	
| d }t|j|dS t| } |  std|  dt | trtd|   t|  t	
| d dS t rddlm} t | |jrtd t }| jpd}| j||d t| d|  dS tdt |  d)zOpen `content` as a binary file, either from a URL, a local path, raw bytes, or a PIL Image.

    Do nothing if `content` is None.
    NreadzReading content from BinaryIOnamer   z3Expected binary stream (bytes), but got text stream)r3   https://http://zDownloading content from zContent-TypezFile not found at z. If `data` is a string, it must either be a URL or a path to a local file. To pass raw content, please encode it as bytes first.zOpening content from r!   zConverting PIL Image to bytesPNG)formatzimage/zUnsupported content type: zl. Expected one of: bytes, bytearray, BinaryIO, memoryview, Path, str (URL or file path), or PIL.Image.Image.)!r7   r/   r2   	bytearray
memoryviewhasattrloggerdebugrL   	mimetypes
guess_typerM   r-   	TypeError
startswithr   getr)   rF   r   existsFileNotFoundError
read_bytesr   rD   r"   ioBytesIOrQ   savegetvaluelowertype)rF   r(   r3   responser"   bufferrQ   r0   r0   r1   rJ      sP   








c                 C   s   t | }t| S )z\Encode a raw file (image, audio) into base64. Can be bytes, an opened file, a path or a URL.)rJ   base64	b64encodedecode)rF   	raw_bytesr0   r0   r1   _b64_encode   s   rk   default_mime_typec                 C   sH   t | tr| dr| S t| }|jp|}t| }d| d| S )N)rO   rN   data:rm   z;base64,)r7   r-   rZ   rJ   r3   rg   rh   ri   )rF   rl   rj   r3   encoded_datar0   r0   r1   _as_url   s   
ro   encoded_imagec                 C   s   t  }|tt| S )z/Parse a base64-encoded string into a PIL Image.)rE   openr_   r`   rg   	b64decode)rp   r"   r0   r0   r1   _b64_to_image   s   rs   c                 C      t |  S )ac  Parse bytes from a Response object into a Python list.

    Expects the response body to be JSON-encoded data.

    NOTE: This is exactly the same implementation as `_bytes_to_dict` and will not complain if the returned data is a
    dictionary. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
    r'   loadsri   rI   r0   r0   r1   _bytes_to_list      rw   c                 C   rt   )ac  Parse bytes from a Response object into a Python dictionary.

    Expects the response body to be JSON-encoded data.

    NOTE: This is exactly the same implementation as `_bytes_to_list` and will not complain if the returned data is a
    list. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
    ru   rI   r0   r0   r1   _bytes_to_dict   rx   ry   c                 C   s   t  }|t| S )zParse bytes from a Response object into a PIL Image.

    Expects the response body to be raw bytes. To deal with b64 encoded images, use `_b64_to_image` instead.
    )rE   rq   r_   r`   )rF   r"   r0   r0   r1   _bytes_to_image	  s   rz   re   c                 C   s   t | tr
t| S | S r4   )r7   r/   r'   rv   )re   r0   r0   r1   _as_dict  s   r{   bytes_output_as_linesdetailsc              	   c   sD    | D ]}zt ||}W n ty   Y  dS w |dur|V  qdS )z*Used in `InferenceClient.text_generation`.N%_format_text_generation_stream_outputStopIterationr|   r}   byte_payloadoutputr0   r0   r1    _stream_text_generation_response  s   r   c              	   C  sN   | 2 z 3 dH W }zt ||}W n ty   Y  dS w |dur#|V  q6 dS )z/Used in `AsyncInferenceClient.text_generation`.Nr~   r   r0   r0   r1   &_async_stream_text_generation_response'  s   r   r   c                 C   s~   |  dsd S |  dkrtd| d}t|dd}|dd ur2t	|d |dt
|}|s=|jjS |S 	Ns   data:s   data: [DONE]z[DONE] signal received.zutf-8rm   z/nerror
error_type)rZ   stripr   ri   r'   rv   lstriprstripr[   _parse_text_generation_errorr   parse_obj_as_instancetokentext)r   r}   payloadjson_payloadr   r0   r0   r1   r   5  s   


r   bytes_linesc              	   c   sB    | D ]}zt |}W n ty   Y  dS w |dur|V  qdS )zFUsed in `InferenceClient.chat_completion` if model is served with TGI.N%_format_chat_completion_stream_outputr   r   itemr   r0   r0   r1    _stream_chat_completion_responseK  s   r   c              	   C  sL   | 2 z3 dH W }zt |}W n ty   Y  dS w |dur"|V  q6 dS )z/Used in `AsyncInferenceClient.chat_completion`.Nr   r   r0   r0   r1   &_async_stream_chat_completion_responseX  s   r   c                 C   sn   |  dsd S |  dkrtd| d}t|dd}|dd ur2t	|d |dt
|S r   )rZ   r   r   ri   r'   rv   r   r   r[   r   r   r   )r   r   r   r0   r0   r1   r   e  s   


r   clientr    r   c                 C  sH   z|j 2 z3 d H W }| V  q6 W |  I d H  d S |  I d H  w r4   )rF   r   close)r   re   r   r0   r0   r1   _async_yield_fromz  s   "r   #_UNSUPPORTED_TEXT_GENERATION_KWARGSr&   unsupported_kwargsc                 C   s   t | g | d S r4   )r   
setdefaultextend)r&   r   r0   r0   r1   '_set_unsupported_text_generation_kwargs  s   r   c                 C   s   t | g S r4   )r   r[   )r&   r0   r0   r1   '_get_unsupported_text_generation_kwargs  s   r   
http_errorc                 C   s^   zt | ddp| j }|d}|d}W n	 ty    | w |dur-t||}|| | )z
    Try to parse text-generation-inference error message and raise HTTPError in any case.

    Args:
        error (`HTTPError`):
            The HTTPError that have been raised.
    response_error_payloadNr   r   )getattrre   r'   r[   	Exceptionr   )r   r   r   r   	exceptionr0   r0   r1   raise_text_generation_error  s   


r   r   r   c                 C   sH   |dkrt | S |dkrt| S |dkrt| S |dkr t| S t| S )N
generationincomplete_generation
overloaded
validation)r   r   r   r   r   )r   r   r0   r0   r1   r     s   r   )Sr<   rg   r_   r'   loggingrW   dataclassesr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   requestsr   huggingface_hub.errorsr   r   r   r   r   r   utilsr   r   r   r   _generated.typesr   r   r?   r   r    	PIL.Imager"   r-   UrlTPathTr/   rR   rS   ContentTTASKS_EXPECTING_IMAGES	getLoggerr*   rU   r#   r2   r@   rC   rE   rJ   rk   ro   rs   rw   ry   rz   r{   boolr   r   r   r   r   r   r   r   r.   r   r   r   r   r0   r0   r0   r1   <module>   s   8 	
			B	





"