a
    þdô7  ã                   @  sò   d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	m
Z
 ddlZddlmZ ddlmZ e	rpddlmZ G d	d
„ d
eƒZG dd„ deeƒZG dd„ deeƒZdddœdd„Zddddœdd„Zdddddœdd„Zdddddœdd„ZdS )zPContains classes and methods related to interpretation for components in Gradio.é    )ÚannotationsN)ÚABCÚabstractmethod)ÚTYPE_CHECKINGÚAny)Úutils)Ú
components)Ú	Interfacec                   @  s6   e Zd Zddœdd„Zdd„ Zddd	d
dœdd„ZdS )ÚInterpretableÚNone)Úreturnc                 C  s   |   ¡  d S ©N)Úset_interpret_parameters©Úself© r   ú^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/interpretation.pyÚ__init__   s    zInterpretable.__init__c                 C  s   dS )z¥
        Set any parameters for interpretation. Properties can be set here to be
        used in get_interpretation_neighbors and get_interpretation_scores.
        Nr   r   r   r   r   r      s    z&Interpretable.set_interpret_parametersr   zlist[Any] | Nonezlist[float]Úlist)ÚxÚ	neighborsÚscoresr   c                 K  s   |S )a£  
        Arrange the output values from the neighbors into interpretation scores for the interface to render.
        Parameters:
            x: Input to interface
            neighbors: Neighboring values to input x used for interpretation.
            scores: Output value corresponding to each neighbor in neighbors
        Returns:
            Arrangement of interpretation scores for interfaces to render.
        r   )r   r   r   r   Úkwargsr   r   r   Úget_interpretation_scores   s    z'Interpretable.get_interpretation_scoresN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r   r   r
      s   r
   c                   @  s6   e Zd Zedddœdd„ƒZeddddœd	d
„ƒZdS )ÚTokenInterpretabler   ztuple[list, list, None]©r   r   c                 C  s
   g g dfS )z™
        Interprets an input data point x by splitting it into a list of tokens (e.g
        a string into words or an image into super-pixels).
        Nr   ©r   r   r   r   r   Útokenize.   s    zTokenInterpretable.tokenizer   z
list[list])ÚtokensÚbinary_mask_matrixr   c                 C  s   g S r   r   )r   r!   r"   r   r   r   Úget_masked_inputs6   s    z$TokenInterpretable.get_masked_inputsN)r   r   r   r   r    r#   r   r   r   r   r   -   s   r   c                   @  s    e Zd Zedddœdd„ƒZdS )ÚNeighborInterpretabler   ztuple[list, dict]r   c                 C  s   g i fS )a²  
        Generates values similar to input to be used to interpret the significance of the input in the final output.
        Parameters:
            x: Input to interface
        Returns: (neighbor_values, interpret_kwargs, interpret_by_removal)
            neighbor_values: Neighboring values to input x to compute for interpretation
            interpret_kwargs: Keyword arguments to be passed to get_interpretation_scores
        r   r   r   r   r   Úget_interpretation_neighbors<   s    
z2NeighborInterpretable.get_interpretation_neighborsN)r   r   r   r   r%   r   r   r   r   r$   ;   s   r$   r	   r   )Ú	interfaceÚ	raw_inputc                 ƒ  s(  t ˆjtƒrÒ‡fdd„tˆjƒD ƒ‰ˆ dˆ¡I dH ‰ˆd ‰tˆjƒdkrTˆg‰g g  }}ttˆˆjƒƒD ]X\‰ \}}|dkrrˆjˆ  ‰tˆƒ‰t ˆt	ƒrtˆ 
|¡\‰}}g }g }	|D ]ˆ}
|
ˆˆ < ‡fdd„tˆjƒD ƒ}ˆ d|¡I dH ‰ˆd ‰tˆjƒdkrˆg‰‡fd	d„tˆjƒD ƒ}|	 |¡ | tˆˆˆƒ¡ qÀ| |	¡ | ˆjˆˆ  |||ˆd
¡ nüt ˆtƒr`ˆ |¡\}}g }g }	|D ]Š}
|
ˆˆ < ‡fdd„tˆjƒD ƒ}ˆ d|¡I dH ‰ˆd ‰tˆjƒdkrîˆg‰‡fdd„tˆjƒD ƒ}|	 |¡ | tˆˆˆƒ¡ qš| |	¡ dd„ |D ƒ}| ˆjˆˆ  ||fi |¤Ž¡ ntdˆ› dƒ‚qn|dks†|dkršzddl}W n4 ttfyÆ } ztdƒ|‚W Y d}~n
d}~0 0 ˆjˆ  ‰t ˆt	ƒsîtdˆ› dƒ‚ˆ 
|¡\‰}}‡ ‡‡‡‡‡fdd„}tˆƒ}| |t d|f¡¡}|jt d|f¡tˆj| ƒdd}|dushJ dƒ‚| ˆjˆˆ  d|d  ¡ |ˆd
¡ | g ¡ qn|du rº| d¡ | g ¡ qntd|› ƒ‚qn||fS ˆjr‡fdd„tˆjƒD ƒ‰ˆj}|ˆŽ }tˆƒdkr|g}|g fS tdƒ‚dS )a1  
    Runs the interpretation command for the machine learning model. Handles both the "default" out-of-the-box
    interpretation for a certain set of UI component types, as well as the custom interpretation case.
    Parameters:
    raw_input: a list of raw inputs to apply the interpretation(s) on.
    c                   s   g | ]\}}|  ˆ | ¡‘qS r   ©Ú
preprocess©Ú.0ÚiÚinput_component©r'   r   r   Ú
<listcomp>Q   s   ÿz!run_interpret.<locals>.<listcomp>r   NÚ
predictioné   Údefaultc                   s   g | ]\}}|  ˆ | ¡‘qS r   r(   r*   ©Úneighbor_raw_inputr   r   r/   g   s   ÿc                   s   g | ]\}}|  ˆ | ¡‘qS r   ©Úpostprocess©r+   r,   Úoutput_component©Úneighbor_outputr   r   r/   t   s   ÿ)Úmasksr!   c                   s   g | ]\}}|  ˆ | ¡‘qS r   r(   r*   r3   r   r   r/   –   s   ÿc                   s   g | ]\}}|  ˆ | ¡‘qS r   r5   r7   r9   r   r   r/   ¢   s   ÿc                 S  s   g | ]
}| ‘qS r   r   )r+   Úscorer   r   r   r/   °   ó    z
Component z  does not support interpretationÚshapZshapleyzVThe package `shap` is required for this interpretation method. Try: `pip install shap`zInput component z' does not support `shap` interpretationc                   sŒ   t ˆtƒsJ ‚ˆ ˆ| ¡}g }|D ]^}t ˆ¡}ˆ |¡|ˆ < t ˆjd|¡}|d }t	ˆj
ƒdkrj|g}tˆˆ|ƒ}| |¡ q"t |¡S )Nr   r0   r1   )Ú
isinstancer   r#   ÚcopyÚdeepcopyr)   Úclient_utilsZsynchronize_asyncÚcall_functionÚlenÚoutput_componentsÚ&get_regression_or_classification_valueÚappendÚnpÚarray)Zbinary_maskZ	masked_xsÚpredsZmasked_xZprocessed_masked_inputZ
new_outputÚpred)r,   r-   r&   Úoriginal_outputÚprocessed_inputr!   r   r   Úget_masked_predictionÍ   s"    
ÿÿz,run_interpret.<locals>.get_masked_predictionT)ZnsamplesZsilentz#SHAP values could not be calculatedzUnknown interpretation method: c                   s   g | ]\}}|  ˆ | ¡‘qS r   r(   r*   r.   r   r   r/   û   s   ÿz#No interpretation method specified.)r?   Úinterpretationr   Ú	enumerateZinput_componentsrC   rD   rE   Úzipr   r    rG   Úquantify_difference_in_labelr   r$   r%   Ú
ValueErrorr>   ÚImportErrorÚModuleNotFoundErrorZKernelExplainerrH   ÚzerosÚshap_valuesZonesÚintZnum_shapÚtolist)r&   r'   r   Zalternative_outputsr   ZinterpZneighbor_valuesr;   Zinterface_scoresZalternative_outputZneighbor_inputZprocessed_neighbor_inputZprocessed_neighbor_outputZinterpret_kwargsr>   ÚerrÚ_rN   Znum_total_segmentsZ	explainerrW   ÚinterpreterrO   r   )	r,   r-   r&   r:   r4   rL   rM   r'   r!   r   Úrun_interpretI   s*   
þ



ÿþÿ

ÿþ
ÿÿ
ûÿ	ÿý
ÿþÿ

ÿþ
ÿÿ
ýüÿ	
ÿÿþ

ÿÿý
ûÿ	


þr]   r   zint | float)ÚoriginalÚ	perturbedr   c                 C  s8   zt | ƒt |ƒ }W n ty2   t| |kƒ}Y n0 |S r   )ÚfloatrS   rX   )r^   r_   r<   r   r   r   Údiff  s
    ra   )r&   rL   Úperturbed_outputr   c                 C  s¦   | j d }| |d ¡}| |d ¡}t|tjƒrz|d }|d }d|v rl|d | }|d | }	||	 }
n
t||ƒ}
|
S t|tjƒr”t||ƒ}
|
S td|› ƒ‚d S )Nr   ÚlabelÚconfidencesúAThis interpretation method doesn't support the Output component: )rE   r6   r?   r   ÚLabelra   ÚNumberrS   )r&   rL   rb   r8   Úpost_original_outputÚpost_perturbed_outputÚoriginal_labelÚperturbed_labelZoriginal_confidenceZperturbed_confidencer<   r   r   r   rR     s$    



ÿrR   c           	      C  sŒ   | j d }| |d ¡}| |d ¡}t|tjƒrz|d }|d }d|v rlt |d | ¡r`dS |d | S t||ƒ}|S td|› ƒ‚dS )zIUsed to combine regression/classification for Shap interpretation method.r   rc   rd   re   N)	rE   r6   r?   r   rf   ÚmathÚisnanra   rS   )	r&   rL   rb   r8   rh   ri   rj   rk   r<   r   r   r   rF   .  s"    
ÿÿrF   )Ú__doc__Ú
__future__r   r@   rl   Úabcr   r   Útypingr   r   ÚnumpyrH   Zgradio_clientr   rB   Zgradior   r	   r
   r   r$   r]   ra   rR   rF   r   r   r   r   Ú<module>   s$    @