a
    
d`$                     @   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
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# 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 Z/ee/e-e,f Z0e1e2Z3G dd dee4Z5dd Z6dd Z7dd Z8da9e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e0ee/ d!d"d#Z>ee#d ee#d  d!d$d#Z>eee0 eee/ ddf d!d%d#Z>e0e+d!d&d'Z?e+d(d)d*d+Z@e.d(d!d,d-ZAe.d(d!d.d/ZBee. eCeee+ ee% f d0d1d2ZDee. eCeee+ ee% f d0d3d4ZEd5d6ee. d7d8d9ZFeG ZHeee+  e:d:< ee+ dd;d<d=ZIee+ eCd;d>d?ZJdS )@zEContains utilities used by both the sync and async inference clients.    N)contextmanager)Path)TYPE_CHECKINGAnyAsyncIterableBinaryIOContextManagerDict	GeneratorIterableListOptionalSetUnionoverload)	HTTPError   )ENDPOINT)build_hf_headersget_sessionhf_raise_for_statusis_aiohttp_availableis_numpy_availableis_pillow_available)Literal   )TextGenerationStreamResponse)ClientResponseClientSessionImagec                   @   s   e Zd ZdZdS )InferenceTimeoutErrorzBError raised when a model is unavailable or the request times out.N)__name__
__module____qualname____doc__ r&   r&   j/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/huggingface_hub/inference/_common.pyr!   D   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_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)r+   r&   r&   r'   _import_numpyT   s    r,   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_image]   s    r.   _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)r0   modelr&   r&   r'   _get_recommended_modelo   s    
r8   )r1   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).0r0   detailsr&   r&   r'   
<dictcomp>   s   z-_fetch_recommended_models.<locals>.<dictcomp>)r/   r   r3   r   r   r   jsonitems)responser&   r&   r'   r2   }   s    
r2   )r?   r1   c                 C   s(   z| d pd W S  t y"   Y d S 0 d S )Nr   )
IndexError)r?   r&   r&   r'   r:      s    r:   )contentr1   c                 C   s   d S Nr&   rB   r&   r&   r'   _open_as_binary   s    rE   c                 C   s   d S rC   r&   rD   r&   r&   r'   rE      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 d   q1 s0    Y  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)
isinstancestr
startswithr5   debugr   r3   rB   r   existsFileNotFoundErroropen)rB   fr&   r&   r'   rE      s    



&c                 C   sP   t | 4}t|tr|n| }t| W  d   S 1 sB0    Y  dS )z[Encode a raw file (image, audio) into base64. Can be byes, an opened file, a path or a URL.N)rE   rG   bytesreadbase64	b64encodedecode)rB   dataZdata_as_bytesr&   r&   r'   _b64_encode   s    
rU   r    )encoded_imager1   c                 C   s   t  }|tt| S )z/Parse a base64-encoded string into a PIL Image.)r.   rM   ioBytesIOrQ   	b64decode)rV   r    r&   r&   r'   _b64_to_image   s    rZ   c                 C   s   t |  S )zyParse bytes from a Response object into a Python dictionary.

    Expects the response body to be encoded-JSON data.
    )r>   loadsrS   rD   r&   r&   r'   _bytes_to_dict   s    r\   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.
    )r.   rM   rW   rX   )rB   r    r&   r&   r'   _bytes_to_image   s    r]   )bytes_output_as_linesr<   r1   c                 c   sb   | D ]X}|dkrq| d}|drt|dd}tf i |}|sV|jjn|V  qd S N   
zutf-8zdata:z/n	rS   rI   r>   r[   lstriprstripr   tokentextr^   r<   byte_payloadpayloadZjson_payloadoutputr&   r&   r'    _stream_text_generation_response   s    

rj   c                 C  sl   | 2 z`3 d H W }|dkrq| d}|drt|dd}tf i |}|s^|jjn|V  q6 d S r_   ra   rf   r&   r&   r'   &_async_stream_text_generation_response   s    

rk   r   r   )clientr@   r1   c                 C  s.   |j 2 z3 d H W }|V  q6 |  I d H  d S rC   )rB   close)rl   r@   rg   r&   r&   r'   _async_yield_from  s    
rn   _NON_TGI_SERVERS)r7   r1   c                 C   s   t |  d S rC   )ro   addr7   r&   r&   r'   _set_as_non_tgi  s    rr   c                 C   s   | t vS rC   )ro   rq   r&   r&   r'   _is_tgi_server   s    rs   )Kr%   rQ   rW   r>   logging
contextlibr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   requestsr   	constantsr   utilsr   r   r   r   r   r   Zutils._typingr   Z_text_generationr   r)   r   r   r-   r    rH   ZUrlTZPathTrO   ZBinaryTZContentT	getLoggerr"   r5   TimeoutErrorr!   r*   r,   r.   r/   __annotations__r8   r2   r:   rE   rU   rZ   r\   r]   boolrj   rk   rn   setro   rr   rs   r&   r&   r&   r'   <module>   s`   < 
		
$