
    j:                     \   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m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 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-dz  de3dz  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<z  de<fd$Z?d%ee'         d&e@dee'         ee$         z  fd'ZAd%ee'         d&e@dee'         ee$         z  fd(ZBd)e'd&e@de'e$z  dz  fd*ZCd+ee'         dee#         fd,ZDd+ee'         dee#         fd-ZEd)e'de#dz  fd.ZFd/ejG        d#ejH        dee'         fd0ZIi ZJe<e'dz  e:e'         f         eKd1<   d2e'dz  d3e:e'         ddfd4ZLd2e'dz  de:e'         fd5ZMd6edefd7ZNd8e'dz  d9e'dz  defd:ZOdS );zEContains utilities used by both the sync and async inference clients.    N)AsyncIterableIterable)	dataclass)Path)TYPE_CHECKINGAnyBinaryIOLiteralNoReturn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                   z    e Zd ZU eed<   eed<   edz  ed<   eez  ez  dz  ed<   edz  ed<   eeef         ed<   dS )RequestParametersurltaskNmodeljsondataheaders)	__name__
__module____qualname__str__annotations__dictlistbytesr        d/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/huggingface_hub/inference/_common.pyr   r   8   sr         	HHH
III:
*t
d
""""
$,#s(^r/   r   c                   F     e Zd ZU dZedz  ed<   ddededz  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'
    ```
    N	mime_typer$   c                     t                                          | |          }||_        t          |t                    r||j        |_        |S N)super__new__r3   
isinstancer2   )clsr$   r3   obj	__class__s       r0   r7   zMimeBytes.__new__S   sF    ggooc4((!dI&& 	+9+< NCM
r/   r5   )	r&   r'   r(   __doc__r)   r*   r-   r7   __classcell__)r;   s   @r0   r2   r2   B   sr           Tz 5 S4Z          r/   r2   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)r@   s    r0   _import_numpyrA   ^   s.     ecdddLLLLr/   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    r0   _import_pil_imagerD   g   sA       
`
 
 	
 Lr/   contentreturnc                     d S r5   r.   rE   s    r0   _open_as_mime_bytesrI   v   s    9<r/   c                     d S r5   r.   rH   s    r0   rI   rI   z   s    BE#r/   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)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.)!r8   r-   r2   	bytearray
memoryviewhasattrloggerdebugrL   	mimetypes
guess_typer)   rM   	TypeError
startswithr   getr%   rE   r   existsFileNotFoundError
read_bytesr   rC   r   ioBytesIOrQ   savegetvaluelowertype)rE   r$   r3   responser   bufferrQ   s          r0   rI   rI   ~   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  r/   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.)rI   base64	b64encodedecode)rE   	raw_bytess     r0   _b64_encoderl      s,    #G,,II&&--///r/   default_mime_typec                     t          | t                    r|                     d          r| S t          |           }|j        p|}t          j        |                                          }d| d| S )N)rO   rN   data:ro   z;base64,)r8   r)   rZ   rI   r3   rh   ri   rj   )rE   rm   rk   r3   encoded_datas        r0   _as_urlrq      s    '3 G$6$67W$X$X  $G,,I #8'8I #I..5577L 5944l444r/   encoded_imagec                     t                      } |j        t          j        t	          j        |                               S )z/Parse a base64-encoded string into a PIL Image.)rD   openr_   r`   rh   	b64decode)rr   r   s     r0   _b64_to_imagerv      s4    E5:bj!1-!@!@AABBBr/   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#   loadsrj   rH   s    r0   _bytes_to_listrz           :gnn&&'''r/   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.
    rx   rH   s    r0   _bytes_to_dictr}      r{   r/   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.
    )rD   rt   r_   r`   )rE   r   s     r0   _bytes_to_imager      s+    
 E5:bj))***r/   re   c                 X    t          | t                    rt          j        |           n| S r5   )r8   r-   r#   ry   )re   s    r0   _as_dictr      s&    #-h#>#>L4:hHLr/   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       r0    _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       r0   &_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 )Nro   data: [DONE][DONE] signal received.z/nerror
error_type)rZ   stripr   lstriprstripr#   ry   r[   _parse_text_generation_errorr   parse_obj_as_instancetokentext)r   r   payloadjson_payloadr   s        r0   r   r     s    ??7## tzz||~%%5666 kk'""))$//G:g&&L   ,*<+@,BRBRS_B`B`aaa (=lKKF$+76<7r/   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      r0    _stream_chat_completion_responser   3  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      r0   &_async_stream_chat_completion_responser   @  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 )Nro   r   r   r   r   )
rZ   r   r   r#   ry   r   r[   r   r   r   )r   r   s     r0   r   r   M  s     ??7## tzz||~%%5666 :dkk'2288::;;L   ,*<+@,BRBRS_B`B`aaa &;LIIIr/   clientc                r   K   |                                 2 3 d {V }|                                W V  6 d S r5   )aiter_linesr   )r   re   r   s      r0   _async_yield_fromr   a  s_      **,,       djjll -,,s   6#_UNSUPPORTED_TEXT_GENERATION_KWARGSr"   unsupported_kwargsc                 b    t                               | g                               |           d S r5   )r   
setdefaultextend)r"   r   s     r0   '_set_unsupported_text_generation_kwargsr   {  s-    '225"==DDEWXXXXXr/   c                 8    t                               | g           S r5   )r   r[   )r"   s    r0   '_get_unsupported_text_generation_kwargsr     s    .225"===r/   
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   )re   getattrr#   r[   	Exceptionr   )r   r   r   r   	exceptions        r0   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     r0   r   r     su    \!!u%%%,,,(///\!!u%%%\!!u%%%r/   )Pr<   rh   r_   r#   loggingrW   collections.abcr   r   dataclassesr   pathlibr   typingr   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-   rR   rS   ContentTTASKS_EXPECTING_IMAGES	getLoggerr&   rU   r   r2   rA   rD   rI   rl   rq   rv   r,   rz   r+   r}   r   r   boolr   r   r   r   r   r   AsyncClientResponser   r   r*   r   r   r   r   r.   r/   r0   <module>r      s   L K K  				       3 3 3 3 3 3 3 3 ! ! ! ! ! !       S S S S S S S S S S S S S S S S S S                   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?D ?Y5E ? ? ? ?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ut| M M M M M3-*.c]X899   $/33-(BCC   8 8d 8sMgGgjnGn 8 8 8 8(
C=
()
 
 
 


-.
 
 
 
J
J$&J J J J(E$5  TabeTf    . DF #T#*d3i*?%@ E E EY3: YSWX[S\ Yae Y Y Y Y>3: >$s) > > > >N x    :	d
 	d
 	Ob 	 	 	 	 	 	r/   