U
    ”Ê¹j¢=  ã                   @   sf  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Z4e 5e6¡Z7eG dd„ dƒƒZ8G dd„ de0ƒZ9dd„ Z:dd„ Z;dd„ Z<ee3e9dœdd„ƒZ=eed ed dœdd„ƒZ=ee3 ee9 dœdd„Z=e3e-dœd d!„Z>e3e-e-d"œd#d$„Z?e-dd%œd&d'„Z@e0edœd(d)„ZAe0edœd*d+„ZBe0ddœd,d-„ZCee0ef ed.œd/d0„ZDee0 eEeee- ee' f d1œd2d3„ZFee0 eEeee- ee' f d1œd4d5„ZGe0eEeee-e'f  d6œd7d8„ZHee0 ee& d9œd:d;„ZIee0 ee& d9œd<d=„ZJe0ee& d>œd?d@„ZKdAdBee0 dCœdDdE„ZLi ZMeee- ee- f eNdF< ee- ee- ddGœdHdI„ZOee- ee- dJœdKdL„ZPeedMœdNdO„ZQee- ee- edPœdQdR„ZRdS )SzEContains 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                   @   s\   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   © r0   r0   ú`/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/inference/_common.pyr#   E   s   
r#   c                       s<   e Zd ZU dZee ed< deee dœ‡ fdd„Z‡  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_typeN)r(   r3   c                    s2   t ƒ  | |¡}||_t|tƒr.|d kr.|j|_|S ©N)ÚsuperÚ__new__r3   Ú
isinstancer2   )Úclsr(   r3   Úobj©Ú	__class__r0   r1   r6   `   s
    zMimeBytes.__new__)N)
r*   r+   r,   Ú__doc__r   r-   r.   r/   r6   Ú__classcell__r0   r0   r:   r1   r2   O   s   
r2   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?   r0   r0   r1   Ú_import_aiohttpk   s    r@   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)rA   r0   r0   r1   Ú_import_numpyt   s    rB   c                  C   s   t ƒ stdƒ‚ddlm}  | S )z,Make sure `PIL` is installed on the machine.z¸Please 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!   r0   r0   r1   Ú_import_pil_image}   s    ÿrD   )ÚcontentÚreturnc                 C   s   d S r4   r0   ©rE   r0   r0   r1   Ú_open_as_mime_bytesŒ   s    rH   c                 C   s   d S r4   r0   rG   r0   r0   r1   rH   �   s    c                 C   sÔ  | dkrdS t | tƒrt| ƒS t | ttfƒr8tt| ƒƒS t| dƒr�t d¡ |  ¡ }t| dƒrnt	 
| j¡d nd}t |tƒr„tdƒ‚t||d�S t | tƒ�r|  d¡s°|  d	¡rüt d
| › �¡ tƒ  | ¡}|j d¡}|dkrît	 
| ¡d }t|j|d�S t| ƒ} |  ¡ �std| › d�ƒ‚t | tƒ�rTt d| › �¡ t|  ¡ t	 
| ¡d d�S tƒ �r¼ddlm} t | |jƒ�r¼t d¡ t ¡ }| j�p’d}| j||d� t| ¡ d| ¡ › �d�S tdt | ƒ› d�ƒ‚dS )z‡Open `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 bytesZ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.)!r7   r/   r2   Ú	bytearrayÚ
memoryviewÚhasattrÚloggerÚdebugrI   Ú	mimetypesÚ
guess_typerJ   r-   Ú	TypeErrorÚ
startswithr   Úgetr)   rE   r   ÚexistsÚFileNotFoundErrorÚ
read_bytesr   rC   r"   ÚioÚBytesIOrM   ÚsaveÚgetvalueÚlowerÚtype)rE   r(   r3   Úresponser"   ÚbufferrM   r0   r0   r1   rH   ”   sP    





ÿ
ÿc                 C   s   t | ƒ}t |¡ ¡ S )z\Encode a raw file (image, audio) into base64. Can be bytes, an opened file, a path or a URL.)rH   Úbase64Ú	b64encodeÚdecode)rE   Ú	raw_bytesr0   r0   r1   Ú_b64_encodeÖ   s    rg   )rE   Údefault_mime_typerF   c                 C   sH   t | tƒr|  d¡r| S t| ƒ}|jp(|}t |¡ ¡ }d|› d|› �S )N)rL   rK   údata:ri   z;base64,)r7   r-   rV   rH   r3   rc   rd   re   )rE   rh   rf   r3   Zencoded_datar0   r0   r1   Ú_as_urlÜ   s    
rj   )Úencoded_imagerF   c                 C   s   t ƒ }| t t | ¡¡¡S )z/Parse a base64-encoded string into a PIL Image.)rD   Úopenr[   r\   rc   Ú	b64decode)rk   r"   r0   r0   r1   Ú_b64_to_imageí   s    rn   c                 C   s   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.
    ©r'   Úloadsre   rG   r0   r0   r1   Ú_bytes_to_listó   s    rq   c                 C   s   t  |  ¡ ¡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.
    ro   rG   r0   r0   r1   Ú_bytes_to_dictþ   s    rr   c                 C   s   t ƒ }| t | ¡¡S )z§Parse 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   rl   r[   r\   )rE   r"   r0   r0   r1   Ú_bytes_to_image	  s    rs   )ra   rF   c                 C   s   t | tƒrt | ¡S | S r4   )r7   r/   r'   rp   )ra   r0   r0   r1   Ú_as_dict  s    rt   )Úbytes_output_as_linesÚdetailsrF   c              	   c   sF   | D ]<}zt ||ƒ}W n tk
r0   Y  qBY nX |dk	r|V  qdS )z*Used in `InferenceClient.text_generation`.N©Ú%_format_text_generation_stream_outputÚStopIteration©ru   rv   Úbyte_payloadÚoutputr0   r0   r1   Ú _stream_text_generation_response  s    r}   c              	   C  sP   | 2 zD3 dH W }zt ||ƒ}W n tk
r8   Y  qLY nX |dk	r|V  q6 dS )z/Used in `AsyncInferenceClient.text_generation`.Nrw   rz   r0   r0   r1   Ú&_async_stream_text_generation_response'  s    r~   )r{   rv   rF   c                 C   s~   |   d¡sd S |  ¡ dkr"tdƒ‚|  d¡}t | d¡ d¡¡}| d¡d k	rdt	|d | d¡ƒ‚t
 |¡}|sz|jjS |S ©	Ns   data:s   data: [DONE]z[DONE] signal received.zutf-8ri   z/nÚerrorÚ
error_type)rV   Ústripry   re   r'   rp   ÚlstripÚrstriprW   Ú_parse_text_generation_errorr   Úparse_obj_as_instanceÚtokenÚtext)r{   rv   ÚpayloadÚjson_payloadr|   r0   r0   r1   rx   5  s    


rx   )Úbytes_linesrF   c              	   c   sD   | D ]:}zt |ƒ}W n tk
r.   Y  q@Y nX |dk	r|V  qdS )zFUsed in `InferenceClient.chat_completion` if model is served with TGI.N©Ú%_format_chat_completion_stream_outputry   ©r‹   Úitemr|   r0   r0   r1   Ú _stream_chat_completion_responseK  s    r�   c              	   C  sN   | 2 zB3 dH W }zt |ƒ}W n tk
r6   Y  qJY nX |dk	r|V  q6 dS )z/Used in `AsyncInferenceClient.chat_completion`.NrŒ   rŽ   r0   r0   r1   Ú&_async_stream_chat_completion_responseX  s    r‘   )r{   rF   c                 C   sn   |   d¡sd S |  ¡ dkr"tdƒ‚|  d¡}t | d¡ d¡¡}| d¡d k	rdt	|d | d¡ƒ‚t
 |¡S r   )rV   r‚   ry   re   r'   rp   rƒ   r„   rW   r…   r   r†   )r{   r‰   rŠ   r0   r0   r1   r�   e  s    

r�   r    r   )Úclientra   rF   c                 C  s:   z$|j2 z3 d H W }| ¡ V  q6 W 5 |   ¡ I d H  X d S r4   )ÚcloserE   r‚   )r’   ra   r{   r0   r0   r1   Ú_async_yield_fromz  s    r”   Ú#_UNSUPPORTED_TEXT_GENERATION_KWARGS)r&   Úunsupported_kwargsrF   c                 C   s   t  | g ¡ |¡ d S r4   )r•   Ú
setdefaultÚextend)r&   r–   r0   r0   r1   Ú'_set_unsupported_text_generation_kwargs˜  s    r™   )r&   rF   c                 C   s   t  | g ¡S r4   )r•   rW   )r&   r0   r0   r1   Ú'_get_unsupported_text_generation_kwargsœ  s    rš   )Ú
http_errorrF   c                 C   sh   z.t | ddƒp| j ¡ }| d¡}| d¡}W n tk
rF   | ‚Y nX |dk	r`t||ƒ}|| ‚| ‚dS )z¸
    Try to parse text-generation-inference error message and raise HTTPError in any case.

    Args:
        error (`HTTPError`):
            The HTTPError that have been raised.
    Zresponse_error_payloadNr€   r�   )Úgetattrra   r'   rW   Ú	Exceptionr…   )r›   r‰   r€   r�   Ú	exceptionr0   r0   r1   Úraise_text_generation_error§  s    



rŸ   )r€   r�   rF   c                 C   sH   |dkrt | ƒS |dkr t| ƒS |dkr0t| ƒS |dkr@t| ƒS t| ƒS )NZ
generationZincomplete_generationZ
overloadedZ
validation)r   r   r   r   r   )r€   r�   r0   r0   r1   r…   Â  s    r…   )Sr<   rc   r[   r'   ÚloggingrS   Údataclassesr   Úpathlibr   Útypingr   r   r   r   r   r	   r
   r   r   r   r   r   Úrequestsr   Zhuggingface_hub.errorsr   r   r   r   r   r   Úutilsr   r   r   r   Z_generated.typesr   r   r?   r   r    Z	PIL.Imager"   r-   ZUrlTZPathTr/   rN   rO   ZContentTZTASKS_EXPECTING_IMAGESÚ	getLoggerr*   rQ   r#   r2   r@   rB   rD   rH   rg   rj   rn   rq   rr   rs   rt   Úboolr}   r~   rx   r�   r‘   r�   r”   r•   r.   r™   rš   rŸ   r…   r0   r0   r0   r1   Ú<module>   s‚   8 	
			B	 þ þ þþþþ