o
    e7                     @  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	r8d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Zd#ddZd$ddZ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                   @  s(   e Zd ZdddZdd ZdddZdS )InterpretablereturnNonec                 C  s   |    d S N)set_interpret_parametersself r   ED:\Projects\ConvertPro\env\Lib\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_parametersxr   	neighborslist[Any] | Nonescoreslist[float]listc                 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)r   r   )r   r   r   r   r   r   r   r   )__name__
__module____qualname__r   r   r   r   r   r   r   r
      s    
r
   c                   @  s(   e Zd ZedddZedddZdS )TokenInterpretabler   r   r   tuple[list, list, None]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.tokenizetokensr   binary_mask_matrix
list[list]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   r   r   r   r"   r&   r   r   r   r   r   -   s
    r   c                   @  s   e Zd ZedddZdS )	NeighborInterpretabler   r   r   tuple[list, dict]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   r   r   r   r'   ;   s    r'   	interfacer	   	raw_inputr   c                   s  t jtrއfddtjD dI dH d tjdkr+gg g }}ttjD ]\ \}}|dkr5j  tt t	r
|\}}g }g }	|D ]C}
|
 < 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
 q8t tr-|\}}g }g }	|D ]C}
|
 < 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 | q8td d|dks?|dkrzddl}W n ttfyY } ztd|d}~ww j  t t	smtd d
|\}} fdd}t}||td|f}|jtd|ftj| dd}|dusJ d|j  d|d  |d
 |g  q8|du r|d |g  q8td| ||fS jrfddtjD j}| }tdkr|g}|g fS td)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                      g | ]\}}|  | qS r   
preprocess.0iinput_componentr+   r   r   
<listcomp>Q       z!run_interpret.<locals>.<listcomp>r   N
prediction   defaultc                   r,   r   r-   r/   neighbor_raw_inputr   r   r4   g   r5   c                   r,   r   postprocessr0   r1   output_componentneighbor_outputr   r   r4   t   r5   )masksr#   c                   r,   r   r-   r/   r9   r   r   r4      r5   c                   r,   r   r;   r=   r?   r   r   r4      r5   c                 S  s   g | ]}| qS r   r   )r0   scorer   r   r   r4      s    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r5|g}t|}|| qt|S )Nr   r6   r7   )
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)r1   r2   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                   r,   r   r-   r/   r3   r   r   r4      r5   z#No interpretation method specified.)rD   interpretationr   	enumerateZinput_componentsrH   rI   rJ   zipr   r"   rL   quantify_difference_in_labelr   r'   r)   
ValueErrorrC   ImportErrorModuleNotFoundErrorZKernelExplainerrM   Zzerosshap_valuesZonesintZnum_shaptolist)r*   r+   r   Zalternative_outputsr   ZinterpZneighbor_valuesrA   Zinterface_scoresZalternative_outputZneighbor_inputZprocessed_neighbor_inputZprocessed_neighbor_outputZinterpret_kwargsrC   err_rS   Znum_total_segmentsZ	explainerr[   interpreterrT   r   )	r1   r2   r*   r@   r:   rQ   rR   r+   r#   r   run_interpretI   s0  









	




	



	


ra   originalr   	perturbedr   int | floatc                 C  s8   zt | t | }W |S  ty   t| |k}Y |S w r   )floatrX   r\   )rb   rc   rB   r   r   r   diff  s   rf   rQ   perturbed_outputc                 C  s   | j d }||d }||d }t|tjr>|d }|d }d|v r7|d | }|d | }	||	 }
|
S t||}
|
S t|tjrKt||}
|
S td| )Nr   labelconfidencesAThis interpretation method doesn't support the Output component: )rJ   r<   rD   r   Labelrf   NumberrX   )r*   rQ   rg   r>   post_original_outputpost_perturbed_outputoriginal_labelperturbed_labelZoriginal_confidenceZperturbed_confidencerB   r   r   r   rW     s&   


rW   c           	      C  s   | j d }||d }||d }t|tjr=|d }|d }d|v r6t|d | r0dS |d | S t||}|S td| )zIUsed to combine regression/classification for Shap interpretation method.r   rh   ri   rj   )	rJ   r<   rD   r   rk   mathisnanrf   rX   )	r*   rQ   rg   r>   rm   rn   ro   rp   rB   r   r   r   rK   .  s"   
rK   )r*   r	   r+   r   )rb   r   rc   r   r   rd   )r*   r	   rQ   r   rg   r   r   rd   )__doc__
__future__r   rE   rq   abcr   r   typingr   r   numpyrM   Zgradio_clientr   rG   Zgradior   r	   r
   r   r'   ra   rf   rW   rK   r   r   r   r   <module>   s&    
 
@
