o
    i:                  	   @   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 ddlZddlmZmZmZmZmZmZmZ ddlmZm Z m!Z! d	d
l"m#Z#m$Z$ erkddl%m&Z& e'Z(ee'e	f Z)ee*ee)e(de+e,f Z-ddhZ.e/e0Z1eG dd dZ2G dd de*Z3dd Z4dd Z5ede-de3fddZ6eded ded fddZ6dee- dee3 fddZ6de-de'fddZ7de-de'de'fd d!Z8d"e'ddfd#d$Z9de*de:fd%d&Z;de*de<fd'd(Z=de*ddfd)d*Z>d+ee*e<f de<fd,d-Z?d.ee' d/e@deee' ee$ f fd0d1ZAd.ee' d/e@deee' ee$ f fd2d3ZBd4e'd/e@deee'e$f  fd5d6ZCd7ee' dee# fd8d9ZDd7ee' dee# fd:d;ZEd4e'dee# fd<d=ZFd>ejGd+ejHdee' fd?d@ZIi ZJe<ee' e:e' f eKdA< dBee' dCe:e' ddfdDdEZLdBee' de:e' fdFdGZMdHedefdIdJZNdKee' dLee' defdMdNZOdS )OzEContains utilities used by both the sync and async inference clients.    N)	dataclass)Path)
TYPE_CHECKINGAnyAsyncIterableBinaryIOIterableLiteralNoReturnOptionalUnionoverload)GenerationErrorHfHubHTTPErrorIncompleteGenerationErrorOverloadedErrorTextGenerationErrorUnknownErrorValidationError   )get_sessionis_numpy_availableis_pillow_available   )ChatCompletionStreamOutputTextGenerationStreamOutput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   dictlistbytesr    r-   r-   g/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/huggingface_hub/inference/_common.pyr   8   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__r0   
isinstancer/   )clsr#   r0   obj	__class__r-   r.   r3   S   s
   zMimeBytes.__new__r1   )
r%   r&   r'   __doc__r   r(   r)   r,   r3   __classcell__r-   r-   r7   r.   r/   B   s   
 $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   ImportErrornumpy)r<   r-   r-   r.   _import_numpy^   s   r=   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   r-   r-   r.   _import_pil_imageg   s   r?   contentreturnc                 C      d S r1   r-   r@   r-   r-   r.   _open_as_mime_bytesv      rD   c                 C   rB   r1   r-   rC   r-   r-   r.   rD   z   rE   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)r0   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.)!r4   r,   r/   	bytearray
memoryviewhasattrloggerdebugrF   	mimetypes
guess_typerG   r(   	TypeError
startswithr   getr$   r@   r   existsFileNotFoundError
read_bytesr   r>   r   ioBytesIOrK   savegetvaluelowertype)r@   r#   r0   responser   bufferrK   r-   r-   r.   rD   ~   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.)rD   base64	b64encodedecode)r@   	raw_bytesr-   r-   r.   _b64_encode   s   re   default_mime_typec                 C   sH   t | tr| dr| S t| }|jp|}t| }d| d| S )N)rI   rH   data:rg   z;base64,)r4   r(   rT   rD   r0   ra   rb   rc   )r@   rf   rd   r0   encoded_datar-   r-   r.   _as_url   s   
ri   encoded_imagec                 C   s   t  }|tt| S )z/Parse a base64-encoded string into a PIL Image.)r?   openrY   rZ   ra   	b64decode)rj   r   r-   r-   r.   _b64_to_image   s   rm   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"   loadsrc   rC   r-   r-   r.   _bytes_to_list      rq   c                 C   rn   )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.
    ro   rC   r-   r-   r.   _bytes_to_dict   rr   rs   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.
    )r?   rk   rY   rZ   )r@   r   r-   r-   r.   _bytes_to_image   s   rt   r_   c                 C   s   t | tr
t| S | S r1   )r4   r,   r"   rp   )r_   r-   r-   r.   _as_dict   s   ru   output_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rv   rw   lineoutputr-   r-   r.    _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`.Nrx   r{   r-   r-   r.   &_async_stream_text_generation_response  s   r   r|   c                 C   sx   |  dsd S |  dkrtd| dd}t|}|dd ur/t|d |dt	
|}|s:|jjS |S )Nrg   data: [DONE][DONE] signal received.z/nerror
error_type)rT   striprz   lstriprstripr"   rp   rU   _parse_text_generation_errorr   parse_obj_as_instancetokentext)r|   rw   payloadjson_payloadr}   r-   r-   r.   ry     s   


ry   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_outputrz   r   r|   r}   r-   r-   r.    _stream_chat_completion_response5  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   r-   r-   r.   &_async_stream_chat_completion_responseB  s   r   c                 C   sb   |  dsd S |  dkrtdt| d }|dd ur,t|d |dt	|S )Nrg   r   r   r   r   )
rT   r   rz   r"   rp   r   rU   r   r   r   )r|   r   r-   r-   r.   r   O  s   

r   clientc                 C  s(   |  2 z3 d H W }| V  q6 d S r1   )aiter_linesr   )r   r_   r|   r-   r-   r.   _async_yield_fromc  s   r   #_UNSUPPORTED_TEXT_GENERATION_KWARGSr!   unsupported_kwargsc                 C   s   t | g | d S r1   )r   
setdefaultextend)r!   r   r-   r-   r.   '_set_unsupported_text_generation_kwargs}  s   r   c                 C   s   t | g S r1   )r   rU   )r!   r-   r-   r.   '_get_unsupported_text_generation_kwargs  s   r   
http_errorc                 C   sl   | j du r| zt| ddp| j  }|d}|d}W n	 ty'   | w |dur4t||}|| | )z
    Try to parse text-generation-inference error message and raise HTTPError in any case.

    Args:
        error (`HTTPError`):
            The HTTPError that have been raised.
    Nresponse_error_payloadr   r   )r_   getattrr"   rU   	Exceptionr   )r   r   r   r   	exceptionr-   r-   r.   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   r-   r-   r.   r     s   r   )Pr9   ra   rY   r"   loggingrQ   dataclassesr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   httpxhuggingface_hub.errorsr   r   r   r   r   r   r   utilsr   r   r   _generated.typesr   r   	PIL.Imager   r(   UrlTPathTr,   rL   rM   ContentTTASKS_EXPECTING_IMAGES	getLoggerr%   rO   r   r/   r=   r?   rD   re   ri   rm   r+   rq   r*   rs   rt   ru   boolr~   r   ry   r   r   r   AsyncClientResponser   r   r)   r   r   r   r   r-   r-   r-   r.   <module>   s   0$

		B	





"