o
    eY                     @  sX  d Z ddlmZ ddlZddlZddlZddlmZmZ ddl	Z	ddl
mZ ddlmZmZ ddlZddlmZmZ ddlmZ dd	lmZ dd
lmZ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rtddl#m$Z$ ddl%m&Z& ed e 				d0d1ddZ'			d2d3ddZ(dd Z)dd  Z*d4d"d#Z+d5d%d&Z,d6d(d)Z-d7d.d/Z.dS )8zThis module should not be used directly as its API is subject to change. Instead,
use the `gr.Blocks.load()` or `gr.load()` functions.    )annotationsN)TYPE_CHECKINGCallable)Client)documentset_documentation_group)
componentsutils)Context)warn_deprecation)ErrorTooManyRequestsError)cols_to_rowsencode_to_base64get_tabular_examplespostprocess_labelrows_to_colsstreamline_spaces_interface)extract_base64_data	to_binary)Blocks)	Interfacehelpersnamestrsrc
str | Noneapi_keyhf_tokenaliasreturnr   c                 K  s0   |du r|rt d |}td| |||d|S )a  
    Method that constructs a Blocks from a Hugging Face repo. Can accept
    model repos (if src is "models") or Space repos (if src is "spaces"). The input
    and output components are automatically loaded from the repo.
    Parameters:
        name: the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
        src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
        api_key: Deprecated. Please use the `hf_token` parameter instead.
        hf_token: optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens.  Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
        alias: optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
    Returns:
        a Gradio Blocks object for the given model
    Example:
        import gradio as gr
        demo = gr.load("gradio/question-answering", src="spaces")
        demo.launch()
    Nz^The `api_key` parameter will be deprecated. Please use the `hf_token` parameter going forward.)r   r   r   r    )r   load_blocks_from_repo)r   r   r   r   r   kwargsr!   r!   ?D:\Projects\ConvertPro\env\Lib\site-packages\gradio/external.pyload&   s   r%   c                 K  s   |du r |  d}t|dksJ d|d }d|dd } tttd}| |v s5J d|  |durKtjdurHtj|krHt	
d |t_|| | ||fi |}|S )	zNCreates and returns a Blocks instance from a Hugging Face model or Space repo.N/   zYEither `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}r   )Zhuggingfacemodelsspaceszparameter: src must be one of zYou are loading a model/Space with a different access token than the one you used to load a previous model/Space. This is not recommended, as it may cause unexpected behavior.)splitlenjoin
from_modelfrom_spaceslowerkeysr
   r   warningswarn)r   r   r   r   r#   tokensZfactory_methodsblocksr!   r!   r$   r"   K   s,   
r"   c                 C  sD   dd d | di}|d ur |d d |d d< |d d |d d< |S )Ninputs)generated_responsespast_user_inputstextconversationr6   r7   r!   )r8   statepayloadr!   r!   r$   chatbot_preprocessq   s   r<   c                 C  s.   |   }tt|d d |d d }||fS )Nr9   r7   r6   )jsonlistzip)responseZresponse_jsonZchatbot_valuer!   r!   r$   chatbot_postprocess   s   

rA   
model_namec              	     s  d|  }d|   t d|  |d urdd| ini tjd d}|jdks3J d	|  d
| di dtjdddddtjddddd dd ddtjdddddtjdddt	t
ddtjdddddtjdddt	dd ddtjddtjddgtjddtjddgttddtjdddtjddddd d d dd!tjdddtjd"ddd#d d$d dd%tjdd&dd'tjd"ddt	d(d dd)tjd*d+dd,tjd-ddgtjd.ddtjd/ddgd0d d1d dd2tjdddtjd3ddd4d d5d dd6tjdddtjd"ddd7d d8d dd9tjdddtjdddd:d d;d dd<tjdddtjd=ddd>d d?d dd@tjdddtjdAdddBd dCd ddDtjdddtjdEddtjdFddgtjd"dddGd dHd ddItjdJdKddLtjd*dMdNddOgtjd"dddPd dQd ddRtjdddtjdSdddTd t
ddUtjdddtjddddVd t
dtjdddtjddddWd dXd dtjddYdd'tjd-ddgtjdZddd[d d\d dtjdd&dd'tjd-ddgtjdZddd]d d^d dtjdd&dd'tjd=ddt	d_d dd`}dav rst| }t|\}}|rQ|ggnd }tjdbdc|t|ddfddetjdfdgdhgdditdjd |dk|< d u s}|vrtdl |  fdmdn}	|d u r| |	_n||	_|	do dp | dqdr}
t|
fi |}dk|ds< tjdti |}|S )uNzhttps://huggingface.co/z,https://api-inference.huggingface.co/models/zFetching model from: AuthorizationBearer GETheaders   zCould not find model: z. If it is a private or gated model, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `api_key` parameter.Zpipeline_tagzaudio-classificationZuploadfilepathZInputF)sourcetypelabelrenderClass)rL   rM   c                 S  s   t S N)r   )ir!   r!   r$   <lambda>       zfrom_model.<locals>.<lambda>c                 S     t dd |  D S )Nc                 S  $   i | ]}|d   dd |d qS rL   z, r   scorer*   .0rP   r!   r!   r$   
<dictcomp>      $ 0from_model.<locals>.<lambda>.<locals>.<dictcomp>r   r=   rr!   r!   r$   rQ          )r5   outputs
preprocesspostprocesszaudio-to-audioOutputzautomatic-speech-recognitionc                 S     |   d S )Nr8   r=   r^   r!   r!   r$   rQ          Zconversational)rM   zfeature-extractionc                 S     d| iS Nr5   r!   xr!   r!   r$   rQ          c                 S  re   )Nr   rf   r^   r!   r!   r$   rQ      rg   z	fill-maskZClassificationc                 S  rh   ri   r!   rj   r!   r!   r$   rQ      rl   c                 S  rS   )Nc                 S     i | ]	}|d  |d qS )Z	token_strrV   r!   rX   r!   r!   r$   rZ          r\   r]   r^   r!   r!   r$   rQ      r`   zimage-classificationzInput Image)rK   rL   rM   c                 S  rS   )Nc                 S  rT   rU   rW   rX   r!   r!   r$   rZ      r[   r\   r]   r^   r!   r!   r$   rQ      r`   zquestion-answering   r
   )linesrL   rM   ZQuestionZAnswerZScorec                 S  s   d| |diS )Nr5   )contextquestionr!   )cqr!   r!   r$   rQ      s    c                 S  s   |   d d|   d ifS )NanswerrL   rV   rf   r^   r!   r!   r$   rQ          ZsummarizationSummaryc                 S  rh   ri   r!   rj   r!   r!   r$   rQ      rl   c                 S     |   d d S )Nr   Zsummary_textrf   r^   r!   r!   r$   rQ          ztext-classificationc                 S  rh   ri   r!   rj   r!   r!   r$   rQ      rl   c                 S  s   t dd |  d D S )Nc                 S  rT   rU   rW   rX   r!   r!   r$   rZ      r[   r\   r   r]   r^   r!   r!   r$   rQ          ztext-generationc                 S  rh   ri   r!   rj   r!   r!   r$   rQ      rl   c                 S  rx   Nr   Zgenerated_textrf   r^   r!   r!   r$   rQ      ry   ztext2text-generationzGenerated Textc                 S  rh   ri   r!   rj   r!   r!   r$   rQ      rl   c                 S  rx   r{   rf   r^   r!   r!   r$   rQ      ry   translationZTranslationc                 S  rh   ri   r!   rj   r!   r!   r$   rQ     rl   c                 S  rx   )Nr   Ztranslation_textrf   r^   r!   r!   r$   rQ     ry   zzero-shot-classificationz&Possible class names (comma-separated)zAllow multiple true classesc                 S  s   | ||ddS )N)Zcandidate_labelsZmulti_class)r5   
parametersr!   )rP   rs   mr!   r!   r$   rQ     s   c                   s&   t  fddtt  d D S )Nc                   s*   i | ]}   d  |    d | qS )labelsZscoresrf   rX   r^   r!   r$   rZ     s    r\   r   )r   ranger+   r=   r^   r!   r^   r$   rQ     s
    
zsentence-similarityzThat is a happy personzSource Sentence)valuerL   rM   z#Separate each sentence by a newlinezSentences to compare to)rp   placeholderrL   rM   c                 S  s   d| dd |  D diS )Nr5   c                 S  s   g | ]}|d kr|qS ) r!   )rY   sr!   r!   r$   
<listcomp>/  s    0from_model.<locals>.<lambda>.<locals>.<listcomp>)Zsource_sentence	sentences)
splitlines)r   r   r!   r!   r$   rQ   ,  s
   c                 S  s   t dd t|  D S )Nc                 S  s   i | ]
\}}d | |qS )z	sentence r!   )rY   rP   vr!   r!   r$   rZ   3  rv   r\   )r   	enumerater=   r^   r!   r!   r$   rQ   2  rz   ztext-to-speechAudioc                 S  rh   ri   r!   rj   r!   r!   r$   rQ   :  rl   ztext-to-imagec                 S  rh   ri   r!   rj   r!   r!   r$   rQ   A  rl   c                 S  rh   ri   r!   rj   r!   r!   r$   rQ   H  rl   c                 S  s   | S rO   r!   r^   r!   r!   r$   rQ   I  rR   zInput DocumentLabelc                 S     dt | |diS Nr5   )imagerr   r   Zimgrt   r!   r!   r$   rQ   R  
   c                 S  rS   )Nc                 S  rm   ru   rV   r!   rX   r!   r!   r$   rZ   Y  rn   r\   r]   r^   r!   r!   r$   rQ   X  r`   c                 S  r   r   r   r   r!   r!   r$   rQ   c  r   c                 S  rS   )Nc                 S  rm   r   r!   rX   r!   r!   r$   rZ   j  rn   r\   r]   r^   r!   r!   r$   rQ   i  r`   c                 S  rx   r{   rf   r^   r!   r!   r$   rQ   t  ry   )token-classificationzdocument-question-answeringzvisual-question-answeringzimage-to-text)ztabular-classificationztabular-regressionz
Input RowsZpandasfixed)rL   rK   rG   Z	col_countrM   ZPredictionsarray
prediction)rL   rK   rG   rM   c                 S  s   dgdd t | jD dS )Nr   c                 S  s   g | ]}|gqS r!   r!   )rY   predr!   r!   r$   r         r   rG   data)r=   loadsr8   r^   r!   r!   r$   rQ     s   )r5   ra   rb   rc   exampleszUnsupported pipeline type: c            	        s   d |  }t |tr|dddii t|}tjd |d}|jdkrU| }d\}}|d	r<d
|d	 }|drId|d }t	d|j | | dkrg| }| d }t
||}d |}|S )Nrb   optionsZwait_for_modelTPOSTr   rH   )r   r   errorz	, Error: r1   z, Warnings: z<Could not complete request to HuggingFace API, Status Code: r   r   rc   )
isinstancedictupdater=   dumpsrequestsrequeststatus_codegetr   r	   Zformat_ner_list)	paramsr   r@   Zerrors_jsonerrorsZwarnsZ
ner_groupsZinput_stringoutputapi_urlrG   pZpipeliner!   r$   query_huggingface_api  s6   




z)from_model.<locals>.query_huggingface_apir5   ra   r   )fnr5   ra   titler   	_api_moder!   )printr   r   r   r=   r   r   r   r   r   r   ZTextboxStateZChatbotr<   rA   Z	DataframeZImageZCheckboxZHighlightedTextr   r   r+   r   
ValueError__name__r   gradior   )rB   r   r   r#   Z	model_urlr@   Z	pipelinesZexample_dataZ	col_namesr   Zinterface_info	interfacer!   r   r$   r-      s  


$+3>KR[bio     &  /
  
a



r-   
space_namec              
   K  s   d|  }t d|  i }|d urd| |d< tjd|  d|d d}|d u r5td	|  d
tj||d}td|j}z
t|	d}	W n t
ya }
 ztd|  |
d }
~
ww d|	v rrt| |	|||fi |S |rytd t| |dS )Nzhttps://huggingface.co/spaces/zFetching Space from: rD   rC   z"https://huggingface.co/api/spaces/z/hostrF   hostzCould not find Space: z. If it is a private or gated Space, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `api_key` parameter.z+window.gradio_config = (.*?);[\s]*</script>r'   zCould not load the Space: Zallow_flaggingzYou cannot override parameters for this Space by passing in kwargs. Instead, please load the Space as a function and use it to create a Blocks or Interface locally. You may find this Guide helpful: https://gradio.app/using_blocks_like_functions/)spacer   )r   r   r   r=   r   researchr8   r   groupAttributeErrorfrom_spaces_interfacer1   r2   from_spaces_blocks)r   r   r   r#   Z	space_urlrG   
iframe_urlr_   resultconfigZaer!   r!   r$   r.     sH   


r.   r   c                 C  s0   t | |d}dd |jD }tj|j||jS )N)r   c                 S  s   g | ]}|j qS r!   )Z_predict_resolve)rY   Zendpointr!   r!   r$   r     r   z&from_spaces_blocks.<locals>.<listcomp>)r   Z	endpointsr   r   Zfrom_configr   r   )r   r   clientZpredict_fnsr!   r!   r$   r     s   r   r   r   r   r   c                   s   t | d ddi|d urd| d<  fdd}|d ur&|n| |_|d< tfi |}d	|d
< tjdi |}|S )Nz/api/predict/zContent-Typezapplication/jsonrD   rC   c               
     s   t d| i} tj | d}t |jd}d|v r&d|d v r&tdz|d }W n ty@ } ztd| |d }~ww t	d d	krM|d
 }t	d d	kr^t
|tr^|d
 }|S )Nr   r   zutf-8r   Z429z)Too many requests to the Hugging Face APIzNCould not find 'data' key in response from external Space. Response received: ra   r'   r   )r=   r   r   postr   contentdecoder   KeyErrorr+   r   r>   )r   r@   r   r   Zker   r   rG   r!   r$   r     s,   z!from_spaces_interface.<locals>.fnr   Tr   r!   )r   r   r   r   r   )rB   r   r   r   r   r#   r   r   r!   r   r$   r     s   
r   )NNNN)r   r   r   r   r   r   r   r   r   r   r    r   )NNN)
r   r   r   r   r   r   r   r   r    r   )rB   r   r   r   r   r   )r   r   r   r   r   r   r    r   )r   r   r   r   r    r   )rB   r   r   r   r   r   r   r   r   r   r    r   )/__doc__
__future__r   r=   r   r1   typingr   r   r   Zgradio_clientr   Zgradio_client.documentationr   r   r   r   r	   Zgradio.contextr
   Zgradio.deprecationr   Zgradio.exceptionsr   r   Zgradio.external_utilsr   r   r   r   r   r   Zgradio.processing_utilsr   r   Zgradio.blocksr   Zgradio.interfacer   r%   r"   r<   rA   r-   r.   r   r   r!   r!   r!   r$   <module>   sL     &&
  
B
0