
    U[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 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j                  d"ej                  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ZOy):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                   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   dictlistbytesr        o/var/www/html/chatbot/Makanify-Chatbot-3/venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr    r    8   sD    	H
IC=
5dD)
**
5/#s(^r0   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__r4   
isinstancer3   )clsr%   r4   obj	__class__s       r1   r8   zMimeBytes.__new__S   s9    goc4(!dI&9+< NNCM
r0   r6   )
r'   r(   r)   __doc__r   r*   r+   r.   r8   __classcell__)r<   s   @r1   r3   r3   B   s0     }5 Xc]  r0   r3   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)rA   s    r1   _import_numpyrB   ^   s    cddLr0   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    r1   _import_pil_imagerE   g   s%     `
 	
 Lr0   contentreturnc                      y r6   r/   rF   s    r1   _open_as_mime_bytesrJ   v   s    9<r0   c                      y r6   r/   rI   s    r1   rJ   rJ   z   s    BEr0   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)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   ~   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 r0   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.)rJ   base64	b64encodedecode)rF   	raw_bytess     r1   _b64_encoderm      s&    #G,II&--//r0   default_mime_typec                     t        | t              r| j                  d      r| S t        |       }|j                  xs |}t        j                  |      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      sn    '3G$6$67W$X $G,I ##8'8I ##I.557L 9+Xl^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      s/    E5::bjj!1!1-!@ABBr0   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$   loadsrk   rI   s    r1   _bytes_to_listr{           ::gnn&''r0   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.
    ry   rI   s    r1   _bytes_to_dictr~      r|   r0   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.
    )rE   ru   r`   ra   )rF   r   s     r1   _bytes_to_imager      s&    
 E5::bjj)**r0   rf   c                 P    t        | t              rt        j                  |       S | S r6   )r9   r.   r$   rz   )rf   s    r1   _as_dictr      s    #-h#>4::hLHLr0   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       r1    _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       r1   &_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 )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#zz|~%566 kk'"))$/G::g&L  ,*<+@,BRBRS_B`aa (==lKF$+6<<77r0   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      r1    _stream_chat_completion_responser   5  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      r1   &_async_stream_chat_completion_responser   B  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 )Nrp   r   r   r   r   )
r[   r   r   r$   rz   r   r\   r   r   r   )r   r   s     r1   r   r   O  s     ??7#zz|~%566 ::dkk'288:;L  ,*<+@,BRBRS_B`aa &;;LIIr0   clientc                l   K   |j                         2 3 d {   }|j                          7 6 y wr6   )aiter_linesr   )r   rf   r   s      r1   _async_yield_fromr   c  s3     **,  djjl,s   4202424#_UNSUPPORTED_TEXT_GENERATION_KWARGSr#   unsupported_kwargsc                 N    t         j                  | g       j                  |       y r6   )r   
setdefaultextend)r#   r   s     r1   '_set_unsupported_text_generation_kwargsr   }  s    '225"=DDEWXr0   c                 .    t         j                  | g       S r6   )r   r\   )r#   s    r1   '_get_unsupported_text_generation_kwargsr     s    .225"==r0   
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   )rf   getattrr$   r\   	Exceptionr   )r   r   r   r   	exceptions        r1   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     r1   r   r     sZ    \!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  	    !  v v v    I H T  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3-*.
8C=(#=>>?$/3
=}-GHHI8
88eC33458,
C=
()


-.
J
J()J(E$5$5  TabeTf . GI #T(3-c*B%C HY8C= YVZ[^V_ Ydh Y>8C= >T#Y >N x :	 	8C= 	Uh 	r0   