U
    9%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rd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< e,e,dddZ>ee,ee, f dd d!Z?ee ee d"d#d$Z@ee1ee0 d%d&d'ZAeed eed  d%d(d'ZAeee1 eee0 ddf d%d)d'ZAe1e,d%d*d+ZBe,d,d-d.d/ZCe/ed%d0d1ZDe/ed%d2d3ZEe/d,d%d4d5ZFee/ eGeee, ee& f d6d7d8ZHee/ eGeee, ee& f d6d9d:ZId;d<ee/ d=d>d?ZJeK ZLeee,  e=d@< ee, ddAdBdCZMee, eGdAdDdEZNdS )FzEContains 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+   `/var/www/html/Darija-Ai-API/env/lib/python3.8/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   s    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)r1   r+   r+   r,   _import_numpyp   s    r2   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    r4   _RECOMMENDED_MODELS)taskreturnc              	   C   sF   t  | }|d k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)r6   modelr+   r+   r,   _get_recommended_model   s    
r>   )r7   c                  C   sB   t d k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).0r6   detailsr+   r+   r,   
<dictcomp>   s     z-_fetch_recommended_models.<locals>.<dictcomp>)r5   r   r9   r   r   r   jsonitems)responser+   r+   r,   r8      s    
r8   )rE   r7   c                 C   s*   z| d pd W S  t k
r$   Y d S X d S )Nr   )
IndexError)rE   r+   r+   r,   r@      s    r@   )contentr7   c                 C   s   d S Nr+   rH   r+   r+   r,   _open_as_binary   s    rK   c                 C   s   d S rI   r+   rJ   r+   r+   r,   rK      s    c              	   c   s   t | trb| ds| drBtd|   t | jV  dS t| } | 	 sbt
d|  dt | trtd|   | d}|V  W 5 Q R X n| 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   r9   rH   r   existsFileNotFoundErroropen)rH   fr+   r+   r,   rK      s    



c              
   C   sD   t | 2}t|tr|n| }t| W  5 Q R  S Q R X dS )z[Encode a raw file (image, audio) into base64. Can be byes, an opened file, a path or a URL.N)rK   rM   bytesreadbase64	b64encodedecode)rH   dataZdata_as_bytesr+   r+   r,   _b64_encode   s    
rZ   r!   )encoded_imager7   c                 C   s   t  }|tt| S )z/Parse a base64-encoded string into a PIL Image.)r4   rR   ioBytesIOrV   	b64decode)r[   r!   r+   r+   r,   _b64_to_image   s    r_   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.
    rD   loadsrX   rJ   r+   r+   r,   _bytes_to_list   s    rb   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.
    r`   rJ   r+   r+   r,   _bytes_to_dict   s    rc   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.
    )r4   rR   r\   r]   )rH   r!   r+   r+   r,   _bytes_to_image   s    rd   )bytes_output_as_linesrB   r7   c                 c   s^   | D ]T}|dkrq| d}|drt|dd}tf |}|sR|jjn|V  qd S N   
zutf-8zdata:z/n	rX   rN   rD   ra   lstriprstripr   tokentextre   rB   byte_payloadpayloadZjson_payloadoutputr+   r+   r,    _stream_text_generation_response  s    


rq   c                 C  sh   | 2 z\3 d H W }|dkrq| d}|drt|dd}tf |}|sZ|jjn|V  q6 d S rf   rh   rm   r+   r+   r,   &_async_stream_text_generation_response  s    


rr   r   r   )clientrF   r7   c                 C  s.   |j 2 z3 d H W }|V  q6 |  I d H  d S rI   )rH   close)rs   rF   rn   r+   r+   r,   _async_yield_from/  s    
ru   _NON_TGI_SERVERS)r=   r7   c                 C   s   t |  d S rI   )rv   addr=   r+   r+   r,   _set_as_non_tgiF  s    ry   c                 C   s   | t kS rI   )rv   rx   r+   r+   r,   _is_tgi_serverJ  s    rz   )Or'   rV   r\   rD   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   r3   r!   r*   ZUrlTZPathTrT   ZBinaryTZContentTZTASKS_EXPECTING_IMAGES	getLoggerr$   r;   r"   TimeoutErrorr-   r0   r2   r4   r5   r)   r>   r8   r@   rK   rZ   r_   rb   rc   rd   r(   rq   rr   ru   setrv   ry   rz   r+   r+   r+   r,   <module>   sl   @ 
		
$  