
    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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j                  d#ej                  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:ZOy);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                   r    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<   y)RequestParametersurltaskNmodeljsondataheaders)	__name__
__module____qualname__str__annotations__dictlistbytesr        r/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr   r   8   sB    	H
I:
*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   s9    goc4(!dI&9+< NNCM
r/   r5   )	r&   r'   r(   __doc__r)   r*   r-   r7   __classcell__)r;   s   @r0   r2   r2   B   s0     Tz5 S4Z  r/   r2   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   ImportErrornumpy)r@   s    r0   _import_numpyrA   ^   s    cddLr/   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   r?   PILr   r   s    r0   _import_pil_imagerD   g   s%     `
 	
 Lr/   contentreturnc                      y r5   r.   rE   s    r0   _open_as_mime_bytesrI   v   s    9<r/   c                      y r5   r.   rH   s    r0   rI   rI   z   s    BEr/   c                    | yt        | t              rt        |       S t        | t        t        f      rt        t        |             S t        | d      rt        j                  d       | j                         }t        | d      r+t        j                  t        | 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)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   ~   sW     '5!!! 'Iz23w(( w45||~BI'SYBZI((W\\):;A>`d	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 r/   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.)rI   base64	b64encodedecode)rE   	raw_bytess     r0   _b64_encoderl      s&    #G,II&--//r/   default_mime_typec                     t        | t              r| j                  d      r| S t        |       }|j                  xs |}t        j                  |      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      sn    '3G$6$67W$X $G,I ##8'8I ##I.557L 9+Xl^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      s/    E5::bjj!1!1-!@ABBr/   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#   loadsrj   rH   s    r0   _bytes_to_listrz           ::gnn&''r/   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.
    rx   rH   s    r0   _bytes_to_dictr}      r{   r/   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.
    )rD   rt   r_   r`   )rE   r   s     r0   _bytes_to_imager      s&    
 E5::bjj)**r/   re   c                 P    t        | t              rt        j                  |       S | S r5   )r8   r-   r#   ry   )re   s    r0   _as_dictr      s    #-h#>4::hLHLr/   output_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   lineoutputs       r0    _stream_text_generation_responser     sH     
  	:4IF 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       r0   &_async_stream_text_generation_responser     sS     
 #  d	:4IF L  		 #s4   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      j	                  d      }t        j                  |      }|j                  d      t        |d   |j                  d            t        j                  |      }|s|j                  j                  S |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#zz|~%566 kk'"))$/G::g&L  ,*<+@,BRBRS_B`aa (==lKF$+6<<77r/   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   r   r   s      r0    _stream_chat_completion_responser   3  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      r0   &_async_stream_chat_completion_responser   @  sQ        d	:4@F L  		 s4   75#57%775	2727c                 N   | j                  d      sy | j                         dk(  rt        d      t        j                  | j                  d      j                               }|j                  d      t        |d   |j                  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#zz|~%566 ::dkk'288:;L  ,*<+@,BRBRS_B`aa &;;LIIr/   clientc                l   K   |j                         2 3 d {   }|j                          7 6 y wr5   )aiter_linesr   )r   re   r   s      r0   _async_yield_fromr   a  s3     **,  djjl,s   4202424#_UNSUPPORTED_TEXT_GENERATION_KWARGSr"   unsupported_kwargsc                 N    t         j                  | g       j                  |       y r5   )r   
setdefaultextend)r"   r   s     r0   '_set_unsupported_text_generation_kwargsr   {  s    '225"=DDEWXr/   c                 .    t         j                  | g       S r5   )r   r[   )r"   s    r0   '_get_unsupported_text_generation_kwargsr     s    .225"==r/   
http_errorc                     | j                   | 	 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.
    Nresponse_error_payloadr   r   )re   getattrr#   r[   	Exceptionr   )r   r   r   r   	exceptions        r0   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     r0   r   r     sZ    \!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      si   L  	    3 !  S S S    I H T  c4i%w	:MN *+;< 			8	$    8	 
 < <i < 
 < 
 E E74= E 
 E?D ?Y5E ?D0 0c 05X 5# 5# 5"C C C(E (d ((E (d (+U +w +Mut| M M3-*.c]X899$/33-(BCC8 8d 8sMgGgjnGn 8(
C=
()


-.
J
J$&J(E$5$5  TabeTf . DF #T#*d3i*?%@ EY3: YSWX[S\ Yae Y>3: >$s) >N x :	d
 	d
 	Ob 	r/   