
    rh>              	       .   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 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/m0Z0 e1Z2ee1ef   Z3ee4ef   Z5ee5e3e2df   Z6ddhZ7 ejp                  e9      Z:e	 G d d             Z;e	 G d d             Z<d Z=d Z>d Z?ede6dee5   fd       Z@eded   deed      fd       Z@edee6   deee5   ddf   fd       Z@de6de1fdZAde6de1de1fd ZBd!e1ddfd"ZCde4defd#ZDde4defd$ZEde4ddfd%ZFd&ee4ef   defd'ZGd(ee4   d)eHdeee1   ee+   f   fd*ZId(ee4   d)eHdeee1   ee+   f   fd+ZJd,e4d)eHdeee1e+f      fd-ZKd.ee4   dee*   fd/ZLd.ee4   dee*   fd0ZMd,e4dee*   fd1ZNd2d3d&d4dee4   fd5ZOi ZPeee1   ee1   f   eQd6<   d7ee1   d8ee1   ddfd9ZRd7ee1   dee1   fd:ZSd;edefd<ZTd=ee1   d>ee1   de!fd?ZUy)@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Imager&   z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        t/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr(   r(   I   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   T   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   u   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t               ryd	d
lm} t        | |j                        r]t        j	                  d       t        j                          }| j#                  || j$                  xs d       |j'                          y|  y# 1 sw Y   yxY ww)zOpen `content` as a binary file, either from a URL, a local path, raw bytes, or a PIL Image.

    Do nothing if `content` is None.

    TODO: handle base64 as input
    https://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 rbr   r%   zConverting PIL Image to bytesPNG)format)
isinstancer2   
startswithloggerdebugr   getrJ   r   existsFileNotFoundErroropenr   rH   r&   ioBytesIOsaverV   getvalue)rJ   fr&   buffers       r7   rO   rO      s9     '3j)W-?-?	-JLL4WI>?-##G,444w-~~#$WI .O O  '4 ,WI67\\$ 	1G	 gu{{+LL89ZZ\FLL(?%L@//## M!	s   CE8E,BE8,E51E8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   rW   bytesreadbase64	b64encodedecode)rJ   r-   data_as_bytess      r7   _b64_encoderl      sN    		! 8T *4 7TYY[.5578 8 8s   AAA$default_mime_typec                    t        | t              r$| j                  d      s| j                  d      r| S d }t        | t        t        f      rt	        j
                  | d      d   }nGt               r=ddlm} t        | |j                        r!d| j                  xs dj                          }|xs |}t        |       }d	| d
| S )NrR   rS   F)strictr   r%   zimage/rU   data:z;base64,)rW   r2   rX   r   	mimetypes
guess_typer   rH   r&   rV   lowerrl   )rJ   rm   	mime_typer&   encoded_datas        r7   _as_urlrv      s    '3W%7%7
%CwGYGYZcGd I'C;'((?B			gu{{+ '.."9E!@!@!B CDI..Iw'L9+Xl^44r6   encoded_imagec                     t               } |j                  t        j                  t	        j
                  |                   S )z/Parse a base64-encoded string into a PIL Image.)rI   r^   r_   r`   rh   	b64decode)rw   r&   s     r7   _b64_to_imagerz      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,   loadsrj   rN   s    r7   _bytes_to_listr~           ::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.
    r|   rN   s    r7   _bytes_to_dictr      r   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   r^   r_   r`   )rJ   r&   s     r7   _bytes_to_imager     s&    
 E5::bjj)**r6   responsec                 P    t        | t              rt        j                  |       S | S rM   )rW   rf   r,   r}   )r   s    r7   _as_dictr     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r   r   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`.Nr   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-8rp   z/nerror
error_type)rX   stripr   rj   r,   r}   lstriprstripr[   _parse_text_generation_errorr"   parse_obj_as_instancetokentext)r   r   payloadjson_payloadr   s        r7   r   r   3  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   I  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   V  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   )rX   r   r   rj   r,   r}   r   r   r[   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 # | j                          d {  7   w xY wwrM   )rJ   r   close)r   r   r   s      r7   _async_yield_fromr   x  sX     "*"2"2 	' 	',$$&&	'"2 llnfllnsM   A)A /-/A /A A)A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    '225"=DDEWXr6   c                 .    t         j                  | g       S rM   )r   r[   )r+   s    r7   '_get_unsupported_text_generation_kwargsr     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   )getattrr   r,   r[   	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   )Vr>   rh   r_   r,   loggingrq   
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PathTrf   BinaryTr4   TASKS_EXPECTING_IMAGES	getLoggerr/   rY   r(   r9   rC   rF   rI   rO   rl   rv   rz   r~   r   r   r   r?   r   r   r   r   r   r   r   r   r3   r   r   r   r   r5   r6   r7   <module>r      s   L  	    % !    "   _ ^ T 5 c4i
x
 %w./ *+;< 			8	$      @	 
""G" 
"
 
(T](GDM"( 
(
 'Xh/ 'Ihw>OQUW[>[4\ ' 'T8 8c 85X 5# 5# 5(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 6 GI #T(3-c*B%C HY8C= YVZ[^V_ Ydh Y>8C= >T#Y >I ( 6	 	8C= 	Uh 	r6   