Ë
    °ëj¶A  ã                   ó”  — 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$ d	dl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. erddl/m0Z0m1Z1 ddl2m3Z3 e4Z5ee4e
f   Z6ee7ef   Z8ee8e6e5f   Z9ddhZ: ejv                  e<«      Z=e G d„ d«      «       Z>d„ Z?d„ Z@d„ ZAdaBeee4ee4   f      eCd<   dee4ee4   f   fd„ZDdee   dee   fd„ZEede9dee8   fd„«       ZFeded   deed      fd„«       ZFedee9   deee8   ddf   fd„«       ZFde9de4fd „ZGd!e4dd"fd#„ZHde7defd$„ZIde7defd%„ZJde7dd"fd&„ZK	 dDd'ee4ee4ef   e9f   d(eee4ef      d)eLdee4ef   fd*„ZMd+ee7   d,eLdeee4   ee.   f   fd-„ZNd+ee7   d,eLdeee4   ee.   f   fd.„ZOd/e7d,eLdeee4e.f      fd0„ZPd1ee7   dee-   fd2„ZQd1ee7   dee-   fd3„ZRd/e7dee-   fd4„ZSd5d6d7d8dee7   fd9„ZTi ZUeee4   ee4   f   eCd:<   d;ee4   d<ee4   ddfd=„ZVd;ee4   dee4   fd>„ZWd?edefd@„ZXdAee4   dBee4   de fdC„ZYy)EzEContains 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é   )ÚENDPOINT)Úbuild_hf_headersÚget_sessionÚhf_raise_for_statusÚis_aiohttp_availableÚis_numpy_availableÚis_pillow_availableé   )ÚChatCompletionStreamOutputÚTextGenerationStreamOutput)ÚClientResponseÚClientSession©ÚImageztext-to-imagezimage-to-imagec                   ó:   — e Zd ZU dZeed<   eed<   eed<   eed<   y)ÚModelStatusaŠ  
    This Dataclass represents the the model status in the Hugging Face Inference API.

    Args:
        loaded (`bool`):
            If the model is currently loaded into Hugging Face's InferenceAPI. 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)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚboolÚ__annotations__Ústrr   © ó    ún/home/oem/CyberBrain26-unified/dev-env/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.pyr+   r+   Q   s   … ñð, ƒLØƒJØÓØ„Nr8   r+   c                  ó8   — t        «       st        d«      ‚dd l} | S )NzMPlease install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).r   )r    ÚImportErrorÚaiohttp)r<   s    r9   Ú_import_aiohttpr=   r   s   € äÔ!ÜÐiÓjÐjÛà€Nr8   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!   r;   Únumpy)r?   s    r9   Ú_import_numpyr@   {   s   € äÔÜÐcÓdÐdÛà€Lr8   c                  ó<   — 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(   s    r9   Ú_import_pil_imagerC   „   s%   € äÔ Üð`ó
ð 	
õ à€Lr8   Ú_RECOMMENDED_MODELSÚreturnc            	      ó  — t         €st        «       j                  t        › d�t	        «       ¬«      } t        | «       | j                  «       j                  «       D ��ci c]  \  }}|t        |d   «      “Œ c}}a t         S c c}}w )Nz
/api/tasks)ÚheadersÚwidgetModels)	rD   r   Úgetr   r   r   ÚjsonÚitemsÚ_first_or_none)ÚresponseÚtaskÚdetailss      r9   Ú_fetch_recommended_modelsrP   –   sw   € äÐ"Ü“=×$Ñ$¬ z°Ð%<ÔFVÓFXÐ$ÓYˆÜ˜HÔ%àOWÏ}É}Ë×OdÑOdÓOf÷
Ù>K¸dÀGˆD”. ¨Ñ!8Ó9Ñ9ó
Ðô Ðùó
s   ÁB rK   c                 ó4   — 	 | d   xs d S # t         $ r Y y w xY w)Nr   )Ú
IndexError)rK   s    r9   rL   rL   ¡   s(   € ðØ�Q‰xÒ˜4ÐøÜò Ùðús   ‚ ‹	–Úcontentc                  ó   — y ©Nr7   ©rS   s    r9   Ú_open_as_binaryrW   «   s   € ð "r8   c                  ó   — y rU   r7   rV   s    r9   rW   rW   ±   s   € ð %(r8   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)	zÂOpen `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)Ú
isinstancer6   Ú
startswithÚloggerÚdebugr   rI   rS   r   ÚexistsÚFileNotFoundErrorÚopen)rS   Úfs     r9   rW   rW   ·   sã   è ø€ ô �'œ3ÔØ×Ñ˜jÔ)¨W×-?Ñ-?À	Ô-JÜ�L‰LÐ4°W°IÐ>Ô?Ü“-×#Ñ# GÓ,×4Ñ4Ò4ØÜ�w“-ˆØ�~‰~ÔÜ#Ø$ W Ið .Oð Oóð ô �'œ4Ô Ü�‰Ð,¨W¨IÐ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 byes, an opened file, a path or a URL.N)rW   r[   ÚbytesÚreadÚbase64Ú	b64encodeÚdecode)rS   ÚdataÚdata_as_bytess      r9   Ú_b64_encoderk   ×   sN   € ä	˜Ó	!ð 8 TÜ *¨4´Ô 7™¸T¿Y¹Y»[ˆÜ×Ñ Ó.×5Ñ5Ó7÷8÷ 8ò 8ús   ŒAAÁA$Úencoded_imager)   c                 ó†   — t        «       } |j                  t        j                  t	        j
                  | «      «      «      S )z/Parse a base64-encoded string into a PIL Image.)rC   ra   ÚioÚBytesIOrf   Ú	b64decode)rl   r)   s     r9   Ú_b64_to_imagerq   Þ   s/   € äÓ€EØˆ5�:‰:”b—j‘j¤×!1Ñ!1°-Ó!@ÓAÓBÐBr8   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.
    ©rJ   Úloadsrh   rV   s    r9   Ú_bytes_to_listru   ä   ó   € ô �:‰:�g—n‘nÓ&Ó'Ð'r8   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.
    rs   rV   s    r9   Ú_bytes_to_dictrx   ï   rv   r8   c                 ó`   — t        «       } |j                  t        j                  | «      «      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.
    )rC   ra   rn   ro   )rS   r)   s     r9   Ú_bytes_to_imagerz   ú   s&   € ô
 Ó€EØˆ5�:‰:”b—j‘j Ó)Ó*Ð*r8   ÚinputsÚ
parametersÚexpect_binaryc                 óh  — |€i }|j                  «       D ��ci c]  \  }}|€Œ	||“Œ }}}t        |«      dkD  }t        | t        t        f«      }|r |st        | t
        «      st        d| › �«      ‚|r|sd| iS |s|rt        d| › �«      ‚i }|rt        | «      |d<   n| |d<   |r||d<   d|iS c c}}w )a$  
    Used in `InferenceClient` and `AsyncInferenceClient` to prepare the payload for an API request, handling various input types and parameters.
    `expect_binary` is set to `True` when the inputs are a binary object or a local path or URL. This is the case for image and audio inputs.
    r   z5Expected binary inputs or a local path or a URL. Got ri   zUnexpected binary inputs. Got r{   r|   rJ   )rK   Úlenr[   rd   r   r6   Ú
ValueErrorrk   )r{   r|   r}   ÚkÚvÚhas_parametersÚ	is_binaryrJ   s           r9   Ú_prepare_payloadr…     sÞ   € ð ÐØˆ
Ø#-×#3Ñ#3Ó#5×G™4˜1˜a¸¹�!�Q‘$ÐG€JÑGÜ˜“_ qÑ(€Nä˜6¤E¬4 =Ó1€Iá™Y¬z¸&Ä#Ô/FÜÐPÐQWÐPXÐYÓZÐZá™^Ø˜ÐÐá™YÜÐ9¸&¸ÐBÓCÐCà€DáÜ$ VÓ,ˆˆXŠð  ˆˆX‰áØ'ˆˆ\ÑØ�Dˆ>Ðùó1 Hs
   ˜
B.£B.Úbytes_output_as_linesrO   c              #   ó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†   rO   Úbyte_payloadÚoutputs       r9   Ú _stream_text_generation_responserŽ   /  sH   è ø€ ð
 .ò ˆð	Ü:¸<ÈÓQˆFð ÑØ‹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       r9   Ú&_async_stream_text_generation_responser�   =  sS   è ø€ ð
 4÷ ð ˆlð	Ü:¸<ÈÓQˆFð ÑØŒLðùô ò 	Úð	úñ 4ùs4   ‚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)r\   ÚstriprŠ   rh   rJ   rt   ÚlstripÚrstriprI   Ú_parse_text_generation_errorr%   Úparse_obj_as_instanceÚtokenÚtext)rŒ   rO   ÚpayloadÚjson_payloadr�   s        r9   r‰   r‰   K  sÀ   € ð ×"Ñ" 8Ô,Øà×ÑÓ˜Ò.ÜÐ5Ó6Ð6ð ×!Ñ! 'Ó*€GÜ—:‘:˜gŸn™n¨WÓ5×<Ñ<¸TÓBÓC€Lð ×Ñ˜Ó Ð,Ü*¨<¸Ñ+@À,×BRÑBRÐS_ÓB`ÓaÐaô (×=Ñ=¸lÓK€FÙ$+ˆ6�<‰<×ÑÐ7°Ð7r8   Ú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      r9   Ú _stream_chat_completion_responser¤   a  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      r9   Ú&_async_stream_chat_completion_responser¦   n  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’   )r\   r•   rŠ   rh   rJ   rt   r–   r—   rI   r˜   r$   r™   )rŒ   rœ   r�   s      r9   r¡   r¡   {  sª   € ð ×"Ñ" 8Ô,Øà×ÑÓ˜Ò.ÜÐ5Ó6Ð6ð ×!Ñ! 'Ó*€GÜ—:‘:˜gŸn™n¨WÓ5×<Ñ<¸TÓBÓC€Lð ×Ñ˜Ó Ð,Ü*¨<¸Ñ+@À,×BRÑBRÐS_ÓB`ÓaÐaô &×;Ñ;¸LÓIÐIr8   Úclientr'   rM   r&   c                ó–   K  — |j                   2 3 d {  –—† }|j                  «       ­–— Œ7 Œ6 | j                  «       ƒ d {  –—†7   y ­wrU   )rS   r•   Úclose)r¨   rM   rŒ   s      r9   Ú_async_yield_fromr«   �  sB   è ø€ Ø&×.Ñ.÷ #ð #ˆlØ× Ñ Ó"Ô"ð#øÐ.à
�,‰,‹.×Òùs+   ‚A	�.“,”.—A	¬.®A	ÁAÁA	Ú#_UNSUPPORTED_TEXT_GENERATION_KWARGSÚmodelÚunsupported_kwargsc                 óN   — t         j                  | g «      j                  |«       y rU   )r¬   Ú
setdefaultÚextend)r­   r®   s     r9   Ú'_set_unsupported_text_generation_kwargsr²   «  s   € Ü'×2Ñ2°5¸"Ó=×DÑDÐEWÕXr8   c                 ó.   — t         j                  | g «      S rU   )r¬   rI   )r­   s    r9   Ú'_get_unsupported_text_generation_kwargsr´   ¯  s   € Ü.×2Ñ2°5¸"Ó=Ð=r8   Ú
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”   )ÚgetattrrM   rJ   rI   Ú	Exceptionr˜   )rµ   rœ   r“   r”   Ú	exceptions        r9   Úraise_text_generation_errorr»   º  s�   € ðä˜*Ð&>ÀÓEÒcÈ×I\ÑI\×IaÑIaÓIcˆØ—‘˜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     r9   r˜   r˜   Õ  sZ   € Ø�\Ò!Ü˜uÓ%Ð%ØÐ,Ò,Ü(¨Ó/Ð/Ø�\Ò!Ü˜uÓ%Ð%Ø�\Ò!Ü˜uÓ%Ð%Ü˜ÓÐr8   )F)Zr3   rf   rn   rJ   Ú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   Ú	constantsr   Úutilsr   r   r   r    r!   r"   Ú_generated.typesr$   r%   r<   r&   r'   Ú	PIL.Imager)   r6   ÚUrlTÚPathTrd   ÚBinaryTÚContentTÚTASKS_EXPECTING_IMAGESÚ	getLoggerr0   r]   r+   r=   r@   rC   rD   r5   rP   rL   rW   rk   rq   ru   rx   rz   r4   r…   rŽ   r�   r‰   r¤   r¦   r¡   r«   r¬   r²   r´   r»   r˜   r7   r8   r9   ú<module>rÒ      s7  ðò Lã Û 	Û Û Ý %Ý !Ý ÷÷ ÷ ÷ õ" ÷÷ õ !÷÷ ÷ Uñ ß5Ýð €Øˆc�4ˆiÑ€Ø
��x�Ñ
 €Ø�˜% Ð%Ñ&€ð *Ð+;Ð<Ð à	ˆ×	Ñ	˜8Ó	$€ð ÷ð ó ðò@òò	ð ;?Ð �X˜d 3¨°©Ð#5Ñ6Ñ7Ó >ð 4¨¨X°c©]Ð(:Ñ#;ó ð˜$˜s™)ð ¨°©ó ð 
ð"Øð"à�GÑò"ó 
ð"ð
 
ð(Ø�T‰]ð(à�G˜D‘MÑ"ò(ó 
ð(ð
 ð˜X hÑ/ð °I¸hÀwÑ>OÐQUÐW[Ð>[Ñ4\ò ó ðð>8˜ð 8 có 8ðC ð C¨ó Cð(˜Eð ( dó (ð(˜Eð ( dó (ð+˜Uð + wó +ð  ñ#Ø�#�t˜C ˜H‘~ xÐ/Ñ0ð#à˜˜c 3˜h™Ñ(ð#ð ð#ð 
ˆ#ˆsˆ(�^ó	#ðRØ# E™?ðØ59ðà
ˆ8�C‰=˜(Ð#=Ñ>Ð>Ñ?óðØ(¨Ñ/ðØ:>ðà
ˆ=˜Ñ˜}Ð-GÑHÐHÑIóð8Øð8Ø"&ð8àˆe�CÐ3Ð3Ñ4Ñ5ó8ð,
Ø˜%‘ð
àÐ(Ñ)ó
ð
Ø˜uÑ%ð
àÐ-Ñ.ó
ðJØðJàÐ(Ñ)óJð* Oð Ð?Oð ÐTaÐbgÑThó ð0 GIÐ # T¨(°3©-¸¸c¹Ð*BÑ%CÓ HðY°8¸C±=ð YÐVZÐ[^ÑV_ð YÐdhó Yð>°8¸C±=ð >ÀTÈ#ÁYó >ð¨Ið ¸(ó ð6	¨°©ð 	À8ÈCÁ=ð 	ÐUhô 	r8   