
    wi=              	          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rd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Z4 ej5        e6          Z7e G d d                      Z8 G d de0          Z9d Z:d Z;d Z<ede3de9fd            Z=eded         ded         fd            Z=dee3         dee9         fdZ=de3de-fdZ>de3de-de-fdZ?d e-ddfd!Z@de0defd"ZAde0defd#ZBde0ddfd$ZCd%ee0ef         defd&ZDd'ee0         d(eEdeee-         ee'         f         fd)ZFd'ee0         d(eEdeee-         ee'         f         fd*ZGd+e0d(eEdeee-e'f                  fd,ZHd-ee0         dee&         fd.ZId-ee0         dee&         fd/ZJd+e0dee&         fd0ZKd1d2d%d3dee0         fd4ZLi ZMeee-         ee-         f         eNd5<   d6ee-         d7ee-         ddfd8ZOd6ee-         dee-         fd9ZPd:edefd;ZQd<ee-         d=ee-         defd>ZRdS )?zEContains 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                       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        y/var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/huggingface_hub/inference/_common.pyr%   r%   E   st         	HHH
IIIC=
5dD)
****
5/#s(^r3   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__r7   
isinstancer6   )clsr*   r7   obj	__class__s       r4   r;   zMimeBytes.__new__`   sF    ggooc4((!dI&& 	+9+< NCM
r3   r9   )
r,   r-   r.   __doc__r   r/   r0   r1   r;   __classcell__)r?   s   @r4   r6   r6   O   sr           } 5 Xc]          r3   r6   c                  H    t                      st          d          dd l} | S )NzMPlease install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).r   )r   ImportErroraiohttp)rD   s    r4   _import_aiohttprE   k   s.    !! kijjjNNNNr3   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   rC   numpy)rG   s    r4   _import_numpyrH   t   s.     ecdddLLLLr3   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   rC   PILr#   r"   s    r4   _import_pil_imagerK   }   sA       
`
 
 	
 Lr3   contentreturnc                     d S r9   r2   rL   s    r4   _open_as_mime_bytesrP      s    9<r3   c                     d S r9   r2   rO   s    r4   rP   rP      s    BE#r3   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
        | 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)r7   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.)!r<   r1   r6   	bytearray
memoryviewhasattrloggerdebugrS   	mimetypes
guess_typerT   r/   	TypeError
startswithr   getr+   rL   r   existsFileNotFoundError
read_bytesr   rJ   r#   ioBytesIOrX   savegetvaluelowertype)rL   r*   r7   responser#   bufferrX   s          r4   rP   rP      s/    t '5!! "!!! 'Iz233 )w((( w 44555||~~=DWf=U=U_I(66q99[_	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  r3   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.)rP   base64	b64encodedecode)rL   	raw_bytess     r4   _b64_encoders      s,    #G,,II&&--///r3   default_mime_typec                     t          | t                    r|                     d          r| S t          |           }|j        p|}t          j        |                                          }d| d| S )N)rV   rU   data:rv   z;base64,)r<   r/   ra   rP   r7   ro   rp   rq   )rL   rt   rr   r7   encoded_datas        r4   _as_urlrx      s    '3 G$6$67W$X$X  $G,,I #8'8I #I..5577L 5944l444r3   encoded_imagec                     t                      } |j        t          j        t	          j        |                               S )z/Parse a base64-encoded string into a PIL Image.)rK   openrf   rg   ro   	b64decode)ry   r#   s     r4   _b64_to_imager}      s4    E5:bj!1-!@!@AABBBr3   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)   loadsrq   rO   s    r4   _bytes_to_listr           :gnn&&'''r3   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.
    r   rO   s    r4   _bytes_to_dictr      r   r3   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.
    )rK   r{   rf   rg   )rL   r#   s     r4   _bytes_to_imager   	  s+    
 E5:bj))***r3   rl   c                 X    t          | t                    rt          j        |           n| S r9   )r<   r1   r)   r   )rl   s    r4   _as_dictr     s&    #-h#>#>L4:hHLr3   bytes_output_as_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   byte_payloadoutputs       r4    _stream_text_generation_responser     sk      
 .  	:<QQFF 	 	 	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       r4   &_async_stream_text_generation_responser   '  s      
 4       l	:<QQFF 	 	 	EEE	LLLL 433s   8
--r   c                    |                      d          sd S |                                 dk    rt          d          |                     d          }t	          j        |                    d                              d                    }|                    d          )t          |d         |                    d                    t          j        |          }|s|j        j        n|S 	Ns   data:s   data: [DONE]z[DONE] signal received.zutf-8rv   z/nerror
error_type)ra   stripr   rq   r)   r   lstriprstriprb   _parse_text_generation_errorr   parse_obj_as_instancetokentext)r   r   payloadjson_payloadr   s        r4   r   r   5  s     ""8,, t..5666 !!'**G:gnnW55<<TBBCCL   ,*<+@,BRBRS_B`B`aaa (=lKKF$+76<7r3   bytes_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   itemr   s      r4    _stream_chat_completion_responser   K  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      r4   &_async_stream_chat_completion_responser   X  s       "       d	:4@@FF 	 	 	EEE	LLLL "kks   7
,,c                    |                      d          sd S |                                 dk    rt          d          |                     d          }t	          j        |                    d                              d                    }|                    d          )t          |d         |                    d                    t          j        |          S r   )ra   r   r   rq   r)   r   r   r   rb   r   r   r   )r   r   r   s      r4   r   r   e  s     ""8,, t..5666 !!'**G:gnnW55<<TBBCCL   ,*<+@,BRBRS_B`B`aaa &;LIIIr3   clientr!   r    c                   K   	 |j         2 3 d {V }|                                W V  6 	 |                                  d {V  d S # |                                  d {V  w xY wr9   )rL   r   close)r   rl   r   s      r4   _async_yield_fromr   z  s      "*"2 	' 	' 	' 	' 	' 	' 	',$$&&&&&&& #3"2 llnnfllnns   A *A A$#_UNSUPPORTED_TEXT_GENERATION_KWARGSr(   unsupported_kwargsc                 b    t                               | g                               |           d S r9   )r   
setdefaultextend)r(   r   s     r4   '_set_unsupported_text_generation_kwargsr     s-    '225"==DDEWXXXXXr3   c                 8    t                               | g           S r9   )r   rb   )r(   s    r4   '_get_unsupported_text_generation_kwargsr     s    .225"===r3   
http_errorc                     	 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.
    response_error_payloadNr   r   )getattrrl   r)   rb   	Exceptionr   )r   r   r   r   	exceptions        r4   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     r4   r   r     su    \!!u%%%,,,(///\!!u%%%\!!u%%%r3   )Sr@   ro   rf   r)   loggingr^   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   rD   r    r!   	PIL.Imager#   r/   UrlTPathTr1   rY   rZ   ContentTTASKS_EXPECTING_IMAGES	getLoggerr,   r\   r%   r6   rE   rH   rK   rP   rs   rx   r}   r   r   r   r   boolr   r   r   r   r   r   r   r   r0   r   r   r   r   r2   r3   r4   <module>r      s   L K K  				       ! ! ! ! ! !                                                       _ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ T T T T T T T T   55555555 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#E?59
8C=(#=>>?   (/:>
=}-GHHI   88"&8eC33458 8 8 8,
%
()
 
 
 

u%
-.
 
 
 
JJ()J J J J*O ?O TabgTh    6 GI #T(3-c*B%C H H HY8C= YVZ[^V_ Ydh Y Y Y Y>8C= >T#Y > > > >I (    6	 	8C= 	Uh 	 	 	 	 	 	r3   