
    Zi:              	          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rd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j/        e0          Z1e G d d                      Z2 G d de*          Z3d Z4d Z5ede-de3fd            Z6eded         ded         fd            Z6dee-         dee3         fdZ6de-de'fdZ7de-de'de'fdZ8de'ddfdZ9de*de:fdZ;de*de<fd Z=de*ddfd!Z>d"ee*e<f         de<fd#Z?d$ee'         d%e@deee'         ee$         f         fd&ZAd$ee'         d%e@deee'         ee$         f         fd'ZBd(e'd%e@deee'e$f                  fd)ZCd*ee'         dee#         fd+ZDd*ee'         dee#         fd,ZEd(e'dee#         fd-ZFd.ejG        d"ejH        dee'         fd/ZIi ZJe<ee'         e:e'         f         eKd0<   d1ee'         d2e:e'         ddfd3ZLd1ee'         de:e'         fd4ZMd5edefd6ZNd7ee'         d8ee'         defd9ZOdS ):zEContains 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                       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        \/root/projects/butler/venv/lib/python3.11/site-packages/huggingface_hub/inference/_common.pyr    r    8   st         	HHH
IIIC=
5dD)
****
5/#s(^r0   r    c                   R     e Zd ZU dZee         ed<   ddedee         f fdZ x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                     t                                          | |          }||_        t          |t                    r||j        |_        |S N)super__new__r4   
isinstancer3   )clsr%   r4   obj	__class__s       r1   r8   zMimeBytes.__new__S   sF    ggooc4((!dI&& 	+9+< NCM
r0   r6   )
r'   r(   r)   __doc__r   r*   r+   r.   r8   __classcell__)r<   s   @r1   r3   r3   B   sr           } 5 Xc]          r0   r3   c                  H    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)rA   s    r1   _import_numpyrB   ^   s.     ecdddLLLLr0   c                  L    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   s    r1   _import_pil_imagerE   g   sA       
`
 
 	
 Lr0   contentreturnc                     d S r6   r/   rF   s    r1   _open_as_mime_bytesrJ   v   s    9<r0   c                     d S r6   r/   rI   s    r1   rJ   rJ   z   s    BE#r0   c                    | dS t          | t                    rt          |           S t          | t          t          f          rt          t          |                     S t          | d          rt                              d           |                                 }t          | d          r,t          j
        t          | j                            d         nd}t          |t                    rt          d          t          ||          S t          | t                    r|                     d          s|                     d	          rt                              d
|             t                                          |           }|j                            d          }|t          j
        |           d         }t          |j        |          S t'          |           } |                                 st+          d|  d          t          | t&                    rXt                              d|             t          |                                 t          j
        |           d                   S t/                      rddlm} t          | |j                  rt                              d           t5          j                    }| j        pd}|                     ||           t          |                                d|                                           S t          dtA          |            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)r4   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.)!r9   r.   r3   	bytearray
memoryviewhasattrloggerdebugrM   	mimetypes
guess_typer*   rN   	TypeError
startswithr   getr&   rF   r   existsFileNotFoundError
read_bytesr   rD   r   ioBytesIOrR   savegetvaluelowertype)rF   r%   r4   responser   bufferrR   s          r1   rJ   rJ   ~   s8    t '5!! "!!! 'Iz233 )w((( w 44555||~~BI'SYBZBZdI(W\):):;;A>>`d	dC   	SQRRR3333 '3 j)) 	DW-?-?	-J-J 	DLL>W>>???"}}((11H (,,^<<I %099!<	X-CCCCw--~~ 	#OW O O O   '4   [6W66777++--9Mg9V9VWX9YZZZZ  Ugu{++ 	ULL8999Z\\F^,uFLLL///V__..:S6<<>>:S:STTTT 	uT']] 	u 	u 	u  r0   c                 l    t          |           }t          j        |                                          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_bytess     r1   _b64_encoderm      s,    #G,,II&&--///r0   default_mime_typec                     t          | t                    r|                     d          r| S t          |           }|j        p|}t          j        |                                          }d| d| S )N)rP   rO   data:rp   z;base64,)r9   r*   r[   rJ   r4   ri   rj   rk   )rF   rn   rl   r4   encoded_datas        r1   _as_urlrr      s    '3 G$6$67W$X$X  $G,,I #8'8I #I..5577L 5944l444r0   encoded_imagec                     t                      } |j        t          j        t	          j        |                               S )z/Parse a base64-encoded string into a PIL Image.)rE   openr`   ra   ri   	b64decode)rs   r   s     r1   _b64_to_imagerw      s4    E5:bj!1-!@!@AABBBr0   c                 N    t          j        |                                           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$   loadsrk   rI   s    r1   _bytes_to_listr{           :gnn&&'''r0   c                 N    t          j        |                                           S )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.
    ry   rI   s    r1   _bytes_to_dictr~      r|   r0   c                 b    t                      } |j        t          j        |                     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   ru   r`   ra   )rF   r   s     r1   _bytes_to_imager      s+    
 E5:bj))***r0   rf   c                 X    t          | t                    rt          j        |           n| S r6   )r9   r.   r$   rz   )rf   s    r1   _as_dictr      s&    #-h#>#>L4:hHLr0   output_linesdetailsc              #   h   K   | D ],}	 t          ||          }n# t          $ r Y  dS w xY w||V  -dS )z*Used in `InferenceClient.text_generation`.N%_format_text_generation_stream_outputStopIterationr   r   lineoutputs       r1    _stream_text_generation_responser     sk      
   	:4IIFF 	 	 	EEE	LLL s   
((c                v   K   | 2 3 d{V }	 t          ||          }n# t          $ r Y  dS w xY w||W V  36 dS )z/Used in `AsyncInferenceClient.text_generation`.Nr   r   s       r1   &_async_stream_text_generation_responser     s      
 #       d	:4IIFF 	 	 	EEE	LLLL #lls   8
--r   c                    |                      d          sd S |                                 dk    rt          d          |                     d                              d          }t          j        |          }|                    d          )t          |d         |                    d                    t          j
        |          }|s|j        j        n|S )Nrp   data: [DONE][DONE] signal received.z/nerror
error_type)r[   stripr   lstriprstripr$   rz   r\   _parse_text_generation_errorr   parse_obj_as_instancetokentext)r   r   payloadjson_payloadr   s        r1   r   r     s     ??7## tzz||~%%5666 kk'""))$//G:g&&L   ,*<+@,BRBRS_B`B`aaa (=lKKF$+76<7r0   linesc              #   f   K   | D ]+}	 t          |          }n# t          $ r Y  dS w xY w||V  ,dS )zFUsed in `InferenceClient.chat_completion` if model is served with TGI.N%_format_chat_completion_stream_outputr   r   r   r   s      r1    _stream_chat_completion_responser   5  si         	:4@@FF 	 	 	EEE	LLL s   
''c                t   K   | 2 3 d{V }	 t          |          }n# t          $ r Y  dS w xY w||W V  26 dS )z/Used in `AsyncInferenceClient.chat_completion`.Nr   r   s      r1   &_async_stream_chat_completion_responser   B  s              d	:4@@FF 	 	 	EEE	LLLL ees   7
,,c                    |                      d          sd S |                                 dk    rt          d          t          j        |                     d                                                    }|                    d          )t          |d         |                    d                    t          j	        |          S )Nrp   r   r   r   r   )
r[   r   r   r$   rz   r   r\   r   r   r   )r   r   s     r1   r   r   O  s     ??7## tzz||~%%5666 :dkk'2288::;;L   ,*<+@,BRBRS_B`B`aaa &;LIIIr0   clientc                r   K   |                                 2 3 d {V }|                                W V  6 d S r6   )aiter_linesr   )r   rf   r   s      r1   _async_yield_fromr   c  s_      **,,       djjll -,,s   6#_UNSUPPORTED_TEXT_GENERATION_KWARGSr#   unsupported_kwargsc                 b    t                               | g                               |           d S r6   )r   
setdefaultextend)r#   r   s     r1   '_set_unsupported_text_generation_kwargsr   }  s-    '225"==DDEWXXXXXr0   c                 8    t                               | g           S r6   )r   r\   )r#   s    r1   '_get_unsupported_text_generation_kwargsr     s    .225"===r0   
http_errorc                    | j         | 	 t          | dd          p| j                                         }|                    d          }|                    d          }n# t          $ r | w xY w|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.
    Nresponse_error_payloadr   r   )rf   getattrr$   r\   	Exceptionr   )r   r   r   r   	exceptions        r1   raise_text_generation_errorr     s     "*&>EEcI\IaIaIcIcG$$[[..

    0
CC	Z' s   AA   A-r   r   c                     |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   s     r1   r   r     su    \!!u%%%,,,(///\!!u%%%\!!u%%%r0   )Pr=   ri   r`   r$   loggingrX   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.   rS   rT   ContentTTASKS_EXPECTING_IMAGES	getLoggerr'   rV   r    r3   rB   rE   rJ   rm   rr   rw   r-   r{   r,   r~   r   r   boolr   r   r   r   r   r   AsyncClientResponser   r   r+   r   r   r   r   r/   r0   r1   <module>r      s%   L K K  				       ! ! ! ! ! !       v v v v v v v v v v v v v v v v v v v v v v v v                   I H H H H H H H H H T T T T T T T T    c4i%w	:MN *+;< 		8	$	$               8  	 	 	 
 < <i < < < 
 < 
 E E74= E E E 
 E?(!3 ?8K ? ? ? ?D0 0c 0 0 0 05X 5# 5# 5 5 5 5"C C C C C C(E (d ( ( ( ((E (d ( ( ( (+U +w + + + +MuUD[) Md M M M M3-*.
8C=(#=>>?   $/3
=}-GHHI   8
88eC33458 8 8 8,
C=
()
 
 
 


-.
 
 
 
J
J()J J J J(E$5  TabeTf    . GI #T(3-c*B%C H H HY8C= YVZ[^V_ Ydh Y Y Y Y>8C= >T#Y > > > >N x    :	 	8C= 	Uh 	 	 	 	 	 	r0   