o
    e*                  	   @   s:  U d 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
 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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$ ddl%m&Z& erwddl'm(Z(m)Z) ddl*m+Z+ e,Z-ee,e
f Z.ee/ef Z0ee0e.e-f Z1ddhZ2e3e4Z5eG dd dZ6G dd dee7Z8dd Z9dd Z:dd Z;da<eee,ee, f  e=d< de,de,fddZ>dee,ee, f fd d!Z?d"ee dee fd#d$Z@ed%e1dee0 fd&d'ZAed%ed deed  fd(d'ZAed%ee1 deee0 ddf fd)d'ZAd%e1de,fd*d+ZBd,e,dd-fd.d/ZCd%e/defd0d1ZDd%e/defd2d3ZEd%e/dd-fd4d5ZFd6ee/ d7eGdeee, ee& f fd8d9ZHd6ee/ d7eGdeee, ee& f fd:d;ZId<d=d>d?dee/ fd@dAZJeK ZLeee,  e=dB< dCee, ddfdDdEZMdCee, deGfdFdGZNdS )HzEContains utilities used by both the sync and async inference clients.    N)contextmanager)	dataclass)Path)TYPE_CHECKINGAnyAsyncIterableBinaryIOContextManagerDict	GeneratorIterableListLiteralOptionalSetUnionoverload)	HTTPError   )ENDPOINT)build_hf_headersget_sessionhf_raise_for_statusis_aiohttp_availableis_numpy_availableis_pillow_available   )TextGenerationStreamResponse)ClientResponseClientSessionImageztext-to-imagezimage-to-imagec                   @   s2   e Zd ZU dZeed< eed< eed< eed< dS )ModelStatusa=  
    This Dataclass represents the the model status in the Hugging Face Inference API.

    Args:
        loaded (`bool`):
            If the model is currently loaded.
        state (`str`):
            The current state of the model. This can be 'Loaded', 'Loadable', 'TooBig'
        compute_type (`str`):
            The type of compute resource the model is using or will use, such as 'gpu' or 'cpu'.
        framework (`str`):
            The name of the framework that the model was built with, such as 'transformers'
            or 'text-generation-inference'.
    ZloadedstateZcompute_typeZ	frameworkN)__name__
__module____qualname____doc__bool__annotations__str r+   r+   QD:\Projects\ConvertPro\env\Lib\site-packages\huggingface_hub/inference/_common.pyr"   I   s   
 r"   c                   @   s   e Zd ZdZdS )InferenceTimeoutErrorzBError raised when a model is unavailable or the request times out.N)r$   r%   r&   r'   r+   r+   r+   r,   r-   `   s    r-   c                  C   s   t  stddd l} | S )NzMPlease install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).r   )r   ImportErroraiohttp)r/   r+   r+   r,   _import_aiohttpg      r0   c                  C   s   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   r.   numpy)r2   r+   r+   r,   _import_numpyp   r1   r3   c                  C   s   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    r+   r+   r,   _import_pil_imagey   s   r5   _RECOMMENDED_MODELStaskreturnc              	   C   sF   t  | }|d u rtd|  dtd| d|  d| d |S )NzTask zn has no recommended task. Please specify a model explicitly. Visit https://huggingface.co/tasks for more info.zUsing recommended model z
 for task z7. Note that it is encouraged to explicitly set `model='zI'` as the recommended models list might get updated without prior notice.)_fetch_recommended_modelsget
ValueErrorloggerinfo)r7   modelr+   r+   r,   _get_recommended_model   s   
r?   c                  C   sB   t d u rt jt dt d} t|  dd |   D a t S )Nz
/api/tasks)headersc                 S   s   i | ]\}}|t |d  qS )ZwidgetModels)_first_or_none).0r7   detailsr+   r+   r,   
<dictcomp>   s    z-_fetch_recommended_models.<locals>.<dictcomp>)r6   r   r:   r   r   r   jsonitems)responser+   r+   r,   r9      s   
r9   rF   c                 C   s$   z| d pd W S  t y   Y d S w )Nr   )
IndexError)rF   r+   r+   r,   rA      s
   rA   contentc                 C      d S Nr+   rI   r+   r+   r,   _open_as_binary      rM   c                 C   rJ   rK   r+   rL   r+   r+   r,   rM      rN   c                 c   s    t | tr2| ds| dr"td|   t | jV  dS t| } | 	 s2t
d|  dt | trZtd|   | d}|V  W d   dS 1 sSw   Y  dS | V  dS )	zOpen `content` as a binary file, either from a URL, a local path, or raw bytes.

    Do nothing if `content` is None,

    TODO: handle a PIL.Image as input
    TODO: handle base64 as input
    zhttps://zhttp://zDownloading content from Nz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 rb)
isinstancer*   
startswithr<   debugr   r:   rI   r   existsFileNotFoundErroropen)rI   fr+   r+   r,   rM      s"   



"
c                 C   sP   t | }t|tr|n| }t| W  d   S 1 s!w   Y  dS )z[Encode a raw file (image, audio) into base64. Can be byes, an opened file, a path or a URL.N)rM   rP   bytesreadbase64	b64encodedecode)rI   dataZdata_as_bytesr+   r+   r,   _b64_encode   s   
$r]   encoded_imager!   c                 C   s   t  }|tt| S )z/Parse a base64-encoded string into a PIL Image.)r5   rU   ioBytesIOrY   	b64decode)r^   r!   r+   r+   r,   _b64_to_image   s   rb   c                 C      t |  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.
    rE   loadsr[   rL   r+   r+   r,   _bytes_to_list      rf   c                 C   rc   )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.
    rd   rL   r+   r+   r,   _bytes_to_dict   rg   rh   c                 C   s   t  }|t| 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.
    )r5   rU   r_   r`   )rI   r!   r+   r+   r,   _bytes_to_image   s   ri   bytes_output_as_linesrC   c                 c   sd    | D ],}|dkr
q| d}|dr/t|dd}tdi |}|s,|jjn|V  qd S N   
zutf-8zdata:z/nr+   	r[   rQ   rE   re   lstriprstripr   tokentextrj   rC   byte_payloadpayloadZjson_payloadoutputr+   r+   r,    _stream_text_generation_response  s   

rv   c                 C  sn   | 2 z03 d H W }|dkrq| d}|dr3t|dd}tdi |}|s0|jjn|V  q6 d S rk   rm   rr   r+   r+   r,   &_async_stream_text_generation_response  s   

rw   clientr   rG   r   c                 C  s0   |j 2 z	3 d H W }|V  q6 |  I d H  d S rK   )rI   close)rx   rG   rs   r+   r+   r,   _async_yield_from/  s
   rz   _NON_TGI_SERVERSr>   c                 C   s   t |  d S rK   )r{   addr>   r+   r+   r,   _set_as_non_tgiF  s   r~   c                 C   s   | t vS rK   )r{   r}   r+   r+   r,   _is_tgi_serverJ  s   r   )Or'   rY   r_   rE   logging
contextlibr   dataclassesr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   requestsr   	constantsr   utilsr   r   r   r   r   r   Z_text_generationr   r/   r   r   r4   r!   r*   ZUrlTZPathTrW   ZBinaryTZContentTZTASKS_EXPECTING_IMAGES	getLoggerr$   r<   r"   TimeoutErrorr-   r0   r3   r5   r6   r)   r?   r9   rA   rM   r]   rb   rf   rh   ri   r(   rv   rw   rz   setr{   r~   r   r+   r+   r+   r,   <module>   sz   @ 
		
 &

