
    ;3h8              	          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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/ e0Z1ee0e
f   Z2ee3ef   Z4ee4e2e1f   Z5ddhZ6 ejn                  e8      Z9e G d d             Z:e G d d             Z;d Z<d Z=d Z>ede5dee4   fd       Z?eded   deed      fd       Z?edee5   deee4   ddf   fd       Z?de5de0fdZ@de0ddfd ZAde3defd!ZBde3defd"ZCde3ddfd#ZDd$ee3ef   defd%ZEd&ee3   d'eFdeee0   ee*   f   fd(ZGd&ee3   d'eFdeee0   ee*   f   fd)ZHd*e3d'eFdeee0e*f      fd+ZId,ee3   dee)   fd-ZJd,ee3   dee)   fd.ZKd*e3dee)   fd/ZLd0d1d$d2dee3   fd3ZMi ZNeee0   ee0   f   eOd4<   d5ee0   d6ee0   ddfd7ZPd5ee0   dee0   fd8ZQd9edefd:ZRd;ee0   d<ee0   de fd=ZSy)>zEContains 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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Imagez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   r   r   ContentTr        a/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr(   r(   H   sE    	H
IC=
5dD)
**
8
#s(^r6   r(   c                   :    e Zd ZU dZeed<   eed<   eed<   eed<   y)ModelStatusas  
    This Dataclass represents the model status in the HF Inference API.

    Args:
        loaded (`bool`):
            If the model is currently loaded into HF's Inference API. Models
            are loaded on-demand, leading to the user's first request taking longer.
            If a model is loaded, you can be assured that it is in a healthy state.
        state (`str`):
            The current state of the model. This can be 'Loaded', 'Loadable', 'TooBig'.
            If a model's state is 'Loadable', it's not too big and has a supported
            backend. Loadable models are automatically loaded when the user first
            requests inference on the endpoint. This means it is transparent for the
            user to load a model, except that the first call takes longer to complete.
        compute_type (`Dict`):
            Information about the compute resource the model is using or will use, such as 'gpu' type and number of
            replicas.
        framework (`str`):
            The name of the framework that the model was built with, such as 'transformers'
            or 'text-generation-inference'.
    loadedstatecompute_type	frameworkN)r/   r0   r1   __doc__boolr3   r2   r   r5   r6   r7   r9   r9   S   s    , LJNr6   r9   c                  8    t               st        d      dd l} | S )NzMPlease install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).r   )r   ImportErroraiohttp)rB   s    r7   _import_aiohttprC   t   s    !ijjNr6   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   rA   numpy)rE   s    r7   _import_numpyrF   }   s    cddLr6   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   rA   PILr&   r%   s    r7   _import_pil_imagerI      s%     `
 	
 Lr6   contentreturnc                      y Nr5   rJ   s    r7   _open_as_binaryrO      s     "r6   c                      y rM   r5   rN   s    r7   rO   rO      s     %(r6   c              #     K   t        | t              r| j                  d      s| j                  d      r>t        j	                  d|         t               j                  |       j                   yt        |       } | j                         st        d|  d      t        | t              r7t        j	                  d|         | j                  d      5 }| ddd       y|  y# 1 sw Y   yxY ww)	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)
isinstancer2   
startswithloggerdebugr   getrJ   r   existsFileNotFoundErroropen)rJ   fs     r7   rO   rO      s      '3j)W-?-?	-JLL4WI>?-##G,444w-~~#$WI .O O  '4 ,WI67\\$ 	1G	 	 		 	s   CC5C)C5)C2.C5c                     t        |       5 }t        |t              r|n|j                         }t	        j
                  |      j                         cddd       S # 1 sw Y   yxY w)z\Encode a raw file (image, audio) into base64. Can be bytes, an opened file, a path or a URL.N)rO   rS   bytesreadbase64	b64encodedecode)rJ   r-   data_as_bytess      r7   _b64_encoderc      sN    		! 8T *4 7TYY[.5578 8 8s   AAA$encoded_imager&   c                     t               } |j                  t        j                  t	        j
                  |                   S )z/Parse a base64-encoded string into a PIL Image.)rI   rZ   ioBytesIOr_   	b64decode)rd   r&   s     r7   _b64_to_imageri      s/    E5::bjj!1!1-!@ABBr6   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,   loadsra   rN   s    r7   _bytes_to_listrm           ::gnn&''r6   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.
    rk   rN   s    r7   _bytes_to_dictrp      rn   r6   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.
    )rI   rZ   rf   rg   )rJ   r&   s     r7   _bytes_to_imagerr      s&    
 E5::bjj)**r6   responsec                 P    t        | t              rt        j                  |       S | S rM   )rS   r]   r,   rl   )rs   s    r7   _as_dictru      s    #-h#>4::hLHLr6   bytes_output_as_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rv   rw   byte_payloadoutputs       r7    _stream_text_generation_responser      sH     
 . 	:<QF 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`.Nry   r|   s       r7   &_async_stream_text_generation_responser     sS     
 4  l	:<QF L  		 4s4   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      }t	        j
                  |j                  d      j                  d            }|j                  d      t        |d   |j                  d            t        j                  |      }|s|j                  j                  S |S 	Ns   data:s   data: [DONE]z[DONE] signal received.zutf-8zdata:z/nerror
error_type)rT   stripr{   ra   r,   rl   lstriprstriprW   _parse_text_generation_errorr"   parse_obj_as_instancetokentext)r}   rw   payloadjson_payloadr~   s        r7   rz   rz     s     ""8,.566 !!'*G::gnnW5<<TBCL  ,*<+@,BRBRS_B`aa (==lKF$+6<<77r6   bytes_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   itemr~   s      r7    _stream_chat_completion_responser   )  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      r7   &_async_stream_chat_completion_responser   6  sQ      "  d	:4@F L  		 "s4   75#57%775	2727c                 r   | j                  d      sy | j                         dk(  rt        d      | j                  d      }t	        j
                  |j                  d      j                  d            }|j                  d      t        |d   |j                  d            t        j                  |      S r   )rT   r   r{   ra   r,   rl   r   r   rW   r   r!   r   )r}   r   r   s      r7   r   r   C  s     ""8,.566 !!'*G::gnnW5<<TBCL  ,*<+@,BRBRS_B`aa &;;LIIr6   clientr$   r#   c                   K   |j                   2 3 d {   }|j                          7 6 | j                          d {  7   y wrM   )rJ   r   close)r   rs   r}   s      r7   _async_yield_fromr   X  sB     &.. # #l  ""#.
,,.s+   A	.,.A	.A	AA	#_UNSUPPORTED_TEXT_GENERATION_KWARGSr+   unsupported_kwargsc                 N    t         j                  | g       j                  |       y rM   )r   
setdefaultextend)r+   r   s     r7   '_set_unsupported_text_generation_kwargsr   s  s    '225"=DDEWXr6   c                 .    t         j                  | g       S rM   )r   rW   )r+   s    r7   '_get_unsupported_text_generation_kwargsr   w  s    .225"==r6   
http_errorc                     	 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.
    response_error_payloadNr   r   )getattrrs   r,   rW   	Exceptionr   )r   r   r   r   	exceptions        r7   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     r7   r   r     sZ    \!u%%,,(//\!u%%\!u%%r6   )Tr>   r_   rf   r,   logging
contextlibr   dataclassesr   pathlibr   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   requestsr   huggingface_hub.errorsr   r   r   r   r   r   utilsr   r   r   r   _generated.typesr!   r"   rB   r#   r$   	PIL.Imager&   r2   UrlTPathTr]   BinaryTr4   TASKS_EXPECTING_IMAGES	getLoggerr/   rU   r(   r9   rC   rF   rI   rO   rc   ri   rm   rp   rr   ru   r?   r   r   rz   r   r   r   r   r   r3   r   r   r   r   r5   r6   r7   <module>r      s   L  	   % !    "   _ ^ T 5 c4i
x
 %%& *+;< 			8	$      @	 
""G" 
"
 
(T](GDM"( 
(
 Xh/ Ihw>OQUW[>[4\  >8 8c 8C C C(E (d ((E (d (+U +w +MuUD[) Md M#E?59
8C=(#=>>?(/:>
=}-GHHI88"&8eC33458,
%
()

u%
-.
JJ()J*O ?O TabgTh 0 GI #T(3-c*B%C HY8C= YVZ[^V_ Ydh Y>8C= >T#Y >I ( 6	 	8C= 	Uh 	r6   