
    ʩh=              	          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jj                  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>ZRy)?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                   r    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<   y)RequestParametersurltaskmodeljsondataheadersN)__name__
__module____qualname__str__annotations__r   r   r	   r   bytesr        _/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr%   r%   E   sD    	H
IC=
5dD)
**
5/#s(^r3   r%   c                   F     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_typer*   c                 |    t         |   | |      }||_        t        |t              r||j                  |_        |S N)super__new__r7   
isinstancer6   )clsr*   r7   obj	__class__s       r4   r;   zMimeBytes.__new__`   s9    goc4(!dI&9+< NNCM
r3   r9   )
r,   r-   r.   __doc__r   r/   r0   r1   r;   __classcell__)r?   s   @r4   r6   r6   O   s0     }5 Xc]  r3   r6   c                  8    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    !ijjNr3   c                  8    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    cddLr3   c                  <    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   }   s%     `
 	
 Lr3   contentreturnc                      y r9   r2   rL   s    r4   _open_as_mime_bytesrP      s    9<r3   c                      y r9   r2   rO   s    r4   rP   rP      s    BEr3   c                 t   | yt        | t              rt        |       S t        | t        t        f      rt        t        |             S t        | d      r}t        j                  d       | j                         }t        | d      r"t        j                  | j                        d   nd}t        |t              rt        d      t        ||      S t        | t              r| j                  d      s| j                  d	      r}t        j                  d
|         t               j!                  |       }|j"                  j!                  d      }|t        j                  |       d   }t        |j$                  |      S t'        |       } | j)                         st+        d|  d      t        | t&              rIt        j                  d|         t        | j-                         t        j                  |       d         S t/               rddlm} t        | |j2                        rxt        j                  d       t5        j6                         }| j8                  xs d}| j;                  ||       t        |j=                         d|j?                                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      sQ     '5!!! 'Iz23w(( w45||~=DWf=UI((6q9[_	dC QRR33 '3j)W-?-?	-JLL4WI>?"}((1H ((,,^<I %009!<	X--CCw-~~#$WI .O O  '4 ,WI67++-9M9Mg9VWX9YZZ gu{{+LL89ZZ\F^^,uFLLL/V__.F6<<>BR:STT 
$T']O 4u 	u r3   c                 ^    t        |       }t        j                  |      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| j                  d      r| S t        |       }|j                  xs |}t        j                  |      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      sn    '3G$6$67W$X $G,I ##8'8I ##I.557L 9+Xl^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}      s/    E5::bjj!1!1-!@ABBr3   c                 H    t        j                  | 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                 H    t        j                  | 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                 `    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::bjj)**r3   rl   c                 P    t        | t              rt        j                  |       S | S r9   )r<   r1   r)   r   )rl   s    r4   _as_dictr     s    #-h#>4::hLHLr3   bytes_output_as_linesdetailsc              #   b   K   | D ]  }	 t        ||      }||  y# t        $ r Y  yw xY ww)z*Used in `InferenceClient.text_generation`.N%_format_text_generation_stream_outputStopIterationr   r   byte_payloadoutputs       r4    _stream_text_generation_responser     sH     
 . 	:<QF L  		s    ///	,/,/c                t   K   | 2 3 d{   }	 t        ||      }|| 7 # t        $ r Y  yw xY w6 yw)z/Used in `AsyncInferenceClient.text_generation`.Nr   r   s       r4   &_async_stream_text_generation_responser   '  sS     
 4  l	:<QF L  		 4s4   86$68&886	3838r   c                    | j                  d      sy | j                         dk(  rt        d      | j                  d      }t	        j
                  |j                  d      j                  d            }|j                  d      t        |d   |j                  d            t        j                  |      }|s|j                  j                  S |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,.566 !!'*G::gnnW5<<TBCL  ,*<+@,BRBRS_B`aa (==lKF$+6<<77r3   bytes_linesc              #   `   K   | D ]  }	 t        |      }||  y# t        $ r Y  yw xY ww)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  sF       	:4@F L  		s    ...	+.+.c                r   K   | 2 3 d{   }	 t        |      }|| 7 # t        $ r Y  yw xY w6 yw)z/Used in `AsyncInferenceClient.chat_completion`.Nr   r   s      r4   &_async_stream_chat_completion_responser   X  sQ      "  d	:4@F L  		 "s4   75#57%775	2727c                 r   | j                  d      sy | j                         dk(  rt        d      | j                  d      }t	        j
                  |j                  d      j                  d            }|j                  d      t        |d   |j                  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,.566 !!'*G::gnnW5<<TBCL  ,*<+@,BRBRS_B`aa &;;LIIr3   clientr!   r    c                   K   	 |j                   2 3 d {   }|j                          7 6 	 | j                          d {  7   y # | j                          d {  7   w xY wwr9   )rL   r   close)r   rl   r   s      r4   _async_yield_fromr   z  sX     "*"2"2 	' 	',$$&&	'"2 llnfllnsM   A)A /-/A /A A)AA)A&A" A&&A)#_UNSUPPORTED_TEXT_GENERATION_KWARGSr(   unsupported_kwargsc                 N    t         j                  | g       j                  |       y r9   )r   
setdefaultextend)r(   r   s     r4   '_set_unsupported_text_generation_kwargsr     s    '225"=DDEWXr3   c                 .    t         j                  | g       S r9   )r   rb   )r(   s    r4   '_get_unsupported_text_generation_kwargsr     s    .225"==r3   
http_errorc                     	 t        | dd      xs | j                  j                         }|j                  d      }|j                  d      }|t        ||      }|| | # t        $ r | w xY w)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cI\I\IaIaIcG$[[.

 0
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     sZ    \!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  	    !       _ ^ T 5 c4i%w	:MN *+;< 			8	$    8	 
 < <i < 
 < 
 E E74= E 
 E?(!3 ?8K ?D0 0c 05X 5# 5# 5"C C C(E (d ((E (d (+U +w +MuUD[) Md M#E?59
8C=(#=>>?(/:>
=}-GHHI88"&8eC33458,
%
()

u%
-.
JJ()J*O ?O TabgTh 6 GI #T(3-c*B%C HY8C= YVZ[^V_ Ydh Y>8C= >T#Y >I ( 6	 	8C= 	Uh 	r3   