a
    dY                  	   @  s  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rddl#m$Z$ ddl%m&Z& ed e d+dddddddddZ'd,ddddddddZ(dd Z)dd Z*ddddddZ+ddddd d!d"Z,dddd#d$d%Z-dd&dddd'd(d)d*Z.dS )-zThis 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)	InterfaceZhelpersstrz
str | Noner   )namesrcapi_keyhf_tokenaliasreturnc                 K  s0   |du r|rt d |}tf | |||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   kwargs r!   X/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/external.pyload&   s    r#   )r   r   r   r   r   c                 K  s   |du r@|  d}t|dks&J d|d }d|dd } tttd}| |v sjJ d|  |durtjdurtj|krt	
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   s0    


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conversationr4   r5   r!   )r6   statepayloadr!   r!   r"   chatbot_preprocessq   s    r:   c                 C  s.   |   }tt|d d |d d }||fS )Nr7   r5   r4   )jsonlistzip)responseZresponse_jsonZchatbot_valuer!   r!   r"   chatbot_postprocess   s    

r?   )
model_namer   r   c                   s@  d|  }d|   t d|  |d ur8dd| ini tjd d}|jdksfJ d	|  d
| dtjdddddtjddddd dd dtjdddddtjdddt	t
dtjdddddtjdddt	dd dtjddtjddgtjddtjddgttdtjdddtjddddd dd dtjdddtjddddd dd dtjdddd tjdddt	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d(d d)d dtjdddtjd*ddd+d d,d dtjdddtjdddd-d d.d dtjdddtjdddd/d d0d dtjdddtjd1ddd2d d3d dtjdddtjd4ddd5d d6d dtjdddtjd7ddtjd8ddgtjdddd9d d:d dtjd;d<dd=tjd"d>d?dd@gtjddddAd dBd dtjdddtjdCdddDd t
dtjdddtjddddEd t
dtjdddtjddddFd dGd dtjddHdd tjd%ddgtjdIdddJd dKd dtjdddd tjd%ddgtjdIdddLd dMd dtjdddd tjd1ddt	dNd ddO}dPv rt| }t|\}}|rZ|ggnd }tjdQdR|t|dSfddTtjdUdVdWgddXtdYd |dZ|< d u s|vrtd[ |  fd\d]}	|d u r| |	_n||	_|	d^ d_ | d`da}
t|
fi |}dbk|dc< tjf i |}|S )dNz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_taguploadfilepathZInputF)sourcetypelabelrenderZClass)rK   rL   c                 S  s   t S N)r   )ir!   r!   r"   <lambda>       zfrom_model.<locals>.<lambda>c                 S  s   t dd |  D S )Nc                 S  s$   i | ]}|d   dd |d qS rK   z, r   scorer(   .0rN   r!   r!   r"   
<dictcomp>   rP   0from_model.<locals>.<lambda>.<locals>.<dictcomp>r   r;   rr!   r!   r"   rO      s   )r3   outputs
preprocesspostprocessZOutputc                 S  s   |   d S )Nr6   r;   rY   r!   r!   r"   rO      rP   )rL   c                 S  s   d| iS Nr3   r!   xr!   r!   r"   rO      rP   c                 S  s   |   d S )Nr   r^   rY   r!   r!   r"   rO      rP   ZClassificationc                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO      rP   c                 S  s   t dd |  D S )Nc                 S  s   i | ]}|d  |d qS )Z	token_strrR   r!   rT   r!   r!   r"   rV      rP   rW   rX   rY   r!   r!   r"   rO      s   zInput Image)rJ   rK   rL   c                 S  s   t dd |  D S )Nc                 S  s$   i | ]}|d   dd |d qS rQ   rS   rT   r!   r!   r"   rV      rP   rW   rX   rY   r!   r!   r"   rO      s      r
   )linesrK   rL   ZQuestionZAnswerZScorec                 S  s   d| |diS )Nr3   )contextquestionr!   )cqr!   r!   r"   rO      rP   c                 S  s   |   d d|   d ifS )NanswerrK   rR   r^   rY   r!   r!   r"   rO      rP   ZSummaryc                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO      rP   c                 S  s   |   d d S )Nr   Zsummary_textr^   rY   r!   r!   r"   rO      rP   c                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO      rP   c                 S  s   t dd |  d D S )Nc                 S  s$   i | ]}|d   dd |d qS rQ   rS   rT   r!   r!   r"   rV      rP   rW   r   rX   rY   r!   r!   r"   rO      s   c                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO      rP   c                 S  s   |   d d S Nr   Zgenerated_textr^   rY   r!   r!   r"   rO      rP   zGenerated Textc                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO      rP   c                 S  s   |   d d S ri   r^   rY   r!   r!   r"   rO      rP   ZTranslationc                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO     rP   c                 S  s   |   d d S )Nr   Ztranslation_textr^   rY   r!   r!   r"   rO     rP   z&Possible class names (comma-separated)zAllow multiple true classesc                 S  s   | ||ddS )N)Zcandidate_labelsZmulti_class)r3   
parametersr!   )rN   rf   mr!   r!   r"   rO     s    c                   s&   t  fddtt  d D S )Nc                   s*   i | ]"}   d  |    d | qS )labelsZscoresr^   rT   rY   r!   r"   rV     s   rW   rl   )r   ranger)   r;   rY   r!   rY   r"   rO     s   
zThat is a happy personzSource Sentence)valuerK   rL   z#Separate each sentence by a newlinezSentences to compare to)rc   placeholderrK   rL   c                 S  s   d| dd |  D diS )Nr3   c                 S  s   g | ]}|d kr|qS ) r!   )rU   sr!   r!   r"   
<listcomp>/  rP   0from_model.<locals>.<lambda>.<locals>.<listcomp>)Zsource_sentence	sentences)
splitlines)r   rt   r!   r!   r"   rO   ,  s
    c                 S  s   t dd t|  D S )Nc                 S  s   i | ]\}}d | |qS )z	sentence r!   )rU   rN   vr!   r!   r"   rV   3  rP   rW   )r   	enumerater;   rY   r!   r!   r"   rO   2  s   Audioc                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO   :  rP   c                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO   A  rP   c                 S  s   d| iS r_   r!   r`   r!   r!   r"   rO   H  rP   c                 S  s   | S rM   r!   rY   r!   r!   r"   rO   I  rP   zInput DocumentLabelc                 S  s   dt | |diS Nr3   )imagere   r   imgrg   r!   r!   r"   rO   R  s
    c                 S  s   t dd |  D S )Nc                 S  s   i | ]}|d  |d qS rh   rR   r!   rT   r!   r!   r"   rV   Y  rP   rW   rX   rY   r!   r!   r"   rO   X  s   c                 S  s   dt | |diS rz   r|   r}   r!   r!   r"   rO   c  s
    c                 S  s   t dd |  D S )Nc                 S  s   i | ]}|d  |d qS r   r!   rT   r!   r!   r"   rV   j  rP   rW   rX   rY   r!   r!   r"   rO   i  s   c                 S  s   |   d d S ri   r^   rY   r!   r!   r"   rO   t  rP   )zaudio-classificationzaudio-to-audiozautomatic-speech-recognitionconversationalzfeature-extractionz	fill-maskzimage-classificationzquestion-answeringZsummarizationztext-classificationztext-generationztext2text-generationtranslationzzero-shot-classificationzsentence-similarityztext-to-speechztext-to-imagetoken-classificationzdocument-question-answeringzvisual-question-answeringzimage-to-text)ztabular-classificationztabular-regressionz
Input RowsZpandasfixed)rK   rJ   rE   Z	col_countrL   ZPredictionsarray
prediction)rK   rJ   rE   rL   c                 S  s   dgdd t | jD dS )Nr   c                 S  s   g | ]
}|gqS r!   r!   )rU   predr!   r!   r"   rr     rP   rs   rE   data)r;   loadsr6   rY   r!   r!   r"   rO     s    )r3   r[   r\   r]   exampleszUnsupported pipeline type: c            	        s   d |  }t |tr2|dddii t|}tjd |d}|jdkr| }d\}}|d	rxd
|d	 }|drd|d }t	d|j | | dkr| }| d }t
||}d |}|S )Nr\   optionsZwait_for_modelTPOSTr   rF   )rp   rp   errorz	, Error: r/   z, Warnings: z<Could not complete request to HuggingFace API, Status Code: r   r   r]   )
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_urlrE   pZpipeliner!   r"   query_huggingface_api  s8    




z)from_model.<locals>.query_huggingface_apir3   r[   r   )fnr3   r[   titler   r   	_api_mode)printr   r   r   r;   r   r   rx   ry   r   r   ZTextboxStateZChatbotr:   r?   Z	DataframeZImageZCheckboxZHighlightedTextr   r   r)   r   
ValueError__name__r   gradior   )r@   r   r   r    Z	model_urlr>   Z	pipelinesZexample_dataZ	col_namesr   Zinterface_info	interfacer!   r   r"   r+      sv   




					
  a




r+   )
space_namer   r   r   c              
   K  s  d|  }t d|  i }|d ur2d| |d< tjd|  d|d d}|d u rjtd	|  d
tj||d}td|j}zt|	d}	W n4 t
y }
 ztd|  |
W Y d }
~
n
d }
~
0 0 d|	v rt| |	|||fi |S |r td t| |dS d S )Nzhttps://huggingface.co/spaces/zFetching Space from: rB   rA   z"https://huggingface.co/api/spaces/z/hostrD   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searchr6   r   groupAttributeErrorfrom_spaces_interfacer/   r0   from_spaces_blocks)r   r   r   r    Z	space_urlrE   
iframe_urlrZ   resultconfigZaer!   r!   r"   r,     sD    


&
r,   )r   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)rU   Zendpointr!   r!   r"   rr     rP   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   r   r   r   r   c                   s   t | d ddi|d ur0d| d<  fdd}|d urL|n| |_|d< tfi |}d	|d
< tjf i |}|S )Nz/api/predict/zContent-Typezapplication/jsonrB   rA   c               
     s   t d| i} tj | d}t |jd}d|v rLd|d v rLtdz|d }W n4 ty } ztd| |W Y d }~n
d }~0 0 t	d d	kr|d
 }t	d d	krt
|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: r[   r%   r   )r;   r   r   postr   contentdecoder   KeyErrorr)   r   r<   )r   r>   r   r   Zker   r   rE   r!   r"   r     s*    z!from_spaces_interface.<locals>.fnr   Tr   )r   r   r   r   r   )r@   r   r   r   r   r    r   r   r!   r   r"   r     s    
r   )NNNN)NNN)/__doc__
__future__r   r;   r   r/   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:   r?   r+   r,   r   r   r!   r!   r!   r"   <module>   sJ        &   &  B0