
    l0j7                        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	rddlmZ  G d	 d
e          Z G d dee          Z G d dee          ZddZddZd dZ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                  $    e Zd ZddZd ZddZdS )InterpretablereturnNonec                .    |                                   d S N)set_interpret_parametersselfs    X/home/wildlama/miniconda3/envs/lam/lib/python3.11/site-packages/gradio/interpretation.py__init__zInterpretable.__init__   s    %%'''''    c                    dS )z
        Set any parameters for interpretation. Properties can be set here to be
        used in get_interpretation_neighbors and get_interpretation_scores.
        N r   s    r   r   z&Interpretable.set_interpret_parameters   s	    
 	r   xr   	neighborslist[Any] | Nonescoreslist[float]listc                    |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   kwargss        r   get_interpretation_scoresz'Interpretable.get_interpretation_scores   s	     r   N)r   r   )r   r   r   r   r   r   r   r   )__name__
__module____qualname__r   r   r!   r   r   r   r   r      sK        ( ( ( (       r   r   c                  >    e Zd Zedd            Zedd
            ZdS )TokenInterpretabler   r   r   tuple[list, list, None]c                    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   s     r   tokenizezTokenInterpretable.tokenize.   s     2t|r   tokensr   binary_mask_matrix
list[list]c                    g S r   r   )r   r+   r,   s      r   get_masked_inputsz$TokenInterpretable.get_masked_inputs6   s    	r   N)r   r   r   r'   )r+   r   r,   r-   r   r   )r"   r#   r$   r   r*   r/   r   r   r   r&   r&   -   sR           ^    ^  r   r&   c                  &    e Zd Zedd            ZdS )NeighborInterpretabler   r   r   tuple[list, dict]c                
    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)   s     r   get_interpretation_neighborsz2NeighborInterpretable.get_interpretation_neighbors<   s     2vr   N)r   r   r   r2   )r"   r#   r$   r   r4   r   r   r   r1   r1   ;   s2        	 	 	 ^	 	 	r   r1   	interfacer
   	raw_inputr   c           
        K   t           j        t                    rfdt           j                  D                                  d           d{V d         t           j                  dk    rgg g }}t          t           j                            D ]x\  \  }}|dk    r j                 t                    t          t                    r)
                    |          \  }}g }g }	|D ]}
|
<   fdt           j                  D             }                     d|           d{V d         t           j                  dk    rgfdt           j                  D             }|	                    |           |                    t                                |                    |	           |                                                 |||	                     kt          t                    r*                    |          \  }}g }g }	|D ]}
|
<   fd
t           j                  D             }                     d|           d{V d         t           j                  dk    rgfdt           j                  D             }|	                    |           |                    t                                |                    |	           d |D             }|                     j                 ||fi |           t!          d d          |dk    s|dk    ro	 ddl}n)# t$          t&          f$ r}t!          d          |d}~ww xY w j                 t          t                    st!          d d          
                    |          \  }} fd}t                    }|                    |t+          j        d|f                    }|                    t+          j        d|f          t3           j        |z            d          }|
J d            |                                                 d|d                                         |	                     |                    g            :|,|                    d           |                    g            ht!          d|           ||fS  j        rFf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                L    g | ] \  }}|                     |                   !S r   
preprocess.0iinput_componentr6   s      r   
<listcomp>z!run_interpret.<locals>.<listcomp>Q   ?     
 
 
"? &&y|44
 
 
r   r   N
prediction   defaultc                L    g | ] \  }}|                     |                   !S r   r9   r<   r=   r>   neighbor_raw_inputs      r   r?   z!run_interpret.<locals>.<listcomp>g   A     4 4 4 2? ,667I!7LMM4 4 4r   c                L    g | ] \  }}|                     |                   !S r   postprocessr<   r=   output_componentneighbor_outputs      r   r?   z!run_interpret.<locals>.<listcomp>t   A     5 5 5 3#3 -889KLL5 5 5r   )masksr+   c                L    g | ] \  }}|                     |                   !S r   r9   rE   s      r   r?   z!run_interpret.<locals>.<listcomp>   rG   r   c                L    g | ] \  }}|                     |                   !S r   rI   rK   s      r   r?   z!run_interpret.<locals>.<listcomp>   rN   r   c                    g | ]}| S r   r   )r<   scores     r   r?   z!run_interpret.<locals>.<listcomp>   s    'M'M'M5'M'M'Mr   z
Component z  does not support interpretationshapshapleyzVThe package `shap` is required for this interpretation method. Try: `pip install shap`zInput component z' does not support `shap` interpretationc                   t          t                    sJ                     |           }g }|D ]}t          j                  }                    |          |<   t          j        	j        d|          }|d         }t          	j
                  dk    r|g}t          	
|          }|                    |           t          j        |          S )Nr   rA   rB   )
isinstancer&   r/   copydeepcopyr:   client_utilssynchronize_asynccall_functionlenoutput_components&get_regression_or_classification_valueappendnparray)binary_mask	masked_xspredsmasked_xprocessed_masked_input
new_outputpredr=   r>   r5   original_outputprocessed_inputr+   s          r   get_masked_predictionz,run_interpret.<locals>.get_masked_prediction   s    %o7IJJJJJ / A A&+ V VIE$- + +151O1O.4C4N4Nx4X4X.q1%1%C%3Q8N& &
 &0%=
y:;;q@@*4JE%
    T****8E??*r   T)nsamplessilentz#SHAP values could not be calculatedzUnknown interpretation method: c                L    g | ] \  }}|                     |                   !S r   r9   r;   s      r   r?   z!run_interpret.<locals>.<listcomp>   r@   r   z#No interpretation method specified.)rW   interpretationr   	enumerateinput_componentsr\   r]   r^   zipr&   r*   r`   quantify_difference_in_labelr!   r1   r4   
ValueErrorrT   ImportErrorModuleNotFoundErrorKernelExplainerra   zerosshap_valuesonesintnum_shaptolist)r5   r6   r   alternative_outputsr   interpneighbor_valuesrO   interface_scoresalternative_outputneighbor_inputprocessed_neighbor_inputprocessed_neighbor_outputinterpret_kwargsrT   err_rl   num_total_segments	explainerrz   interpreterrp   r=   r>   rM   rF   rj   rk   r+   s   ``                     @@@@@@@r   run_interpretr   I   s      )*D11 u@
 
 
 
&/	0J&K&K
 
 
 !* 7 7? K KKKKKKK),7y*++q00./O&("#'Iy7O(P(PQQ [	M [	MNA{6"""+"<Q"?%))__"o/ABB [5D5M5Ma5P5P2FOU')$)+&*9  0>*1-4 4 4 46? ) :7 74 4 40 1:0G0G71 1 + + + + + + +:,*Gy:;;q@@/>.?O5 5 5 57@ ) ;8 85 5 51 +112KLLL(//8 )?O    
 (../ABBBMM'AA%aL+,"'#) B       1FGG 1 (DD '( (*$)+&*9  0>*1-4 4 4 46? ) :7 74 4 40 1:0G0G71 1 + + + + + + +:,*Gy:;;q@@/>.?O5 5 5 57@ ) ;8 85 5 51 +112KLLL(//8 )?O    
 (../ABBB'M'M<L'M'M'M$MMAA%aL+,  /	     %V_VVV   6!!Vy%8%8KKKK#%89   $p  #,"<Q"?!/3EFF $c?ccc   $3#;#;A#>#> 5+ + + + + + + + + +& &)[[" 00)28Q8J4K+L+L 	 (33GQ 2344 !36H!HII 4  
 #..0U...#==!!#A--//#% >     $**2....d####**2.... !K6!K!KLLL***		! @
 
 
 
&/	0J&K&K
 
 
  .$o6y>>Q,-Nr!!>???s   8M==N#NN#originalr   	perturbedr   int | floatc                    	 t          |           t          |          z
  }n## t          $ r t          | |k              }Y nw xY w|S r   )floatru   r|   )r   r   rS   s      r   diffr     sW    +h%	"2"22 + + +H	)**+Ls   " AArj   perturbed_outputc                   | j         d         }|                    |d                   }|                    |d                   }t          |t          j                  rH|d         }|d         }d|v r"|d         |         }|d         |         }	||	z
  }
nt          ||          }
|
S t          |t          j                  rt          ||          }
|
S t          d|           )Nr   labelconfidencesAThis interpretation method doesn't support the Output component: )r^   rJ   rW   r	   Labelr   Numberru   )r5   rj   r   rL   post_original_outputpost_perturbed_outputoriginal_labelperturbed_labeloriginal_confidenceperturbed_confidencerS   s              r   rt   rt     s
    !215+778JKK,889I!9LMM"J$455 
-g6/8 000"1!"4^"D#3A#6~#F '*>>EE99E	$j&7	8	8 
)+@AA bP`bb
 
 	
r   c                   | j         d         }|                    |d                   }|                    |d                   }t          |t          j                  rV|d         }|d         }d|v r0t          j        |d         |                   rdS |d         |         S t          ||          }|S t          d|           )zIUsed to combine regression/classification for Shap interpretation method.r   r   r   r   )	r^   rJ   rW   r	   r   mathisnanr   ru   )	r5   rj   r   rL   r   r   r   r   rS   s	            r   r_   r_   .  s     !215+778JKK,889I!9LMM"J$455 
-g6/8 000z*1-n=>> q#A&~66 E  bP`bb
 
 	
r   )r5   r
   r6   r   )r   r   r   r   r   r   )r5   r
   rj   r   r   r   r   r   )__doc__
__future__r   rX   r   abcr   r   typingr   r   numpyra   gradio_clientr   rZ   gradior	   r
   r   r&   r1   r   r   rt   r_   r   r   r   <module>r      s   V V " " " " " "   # # # # # # # # % % % % % % % %     / / / / / /       !          C   4           M3   |@ |@ |@ |@~   
 
 
 
<
 
 
 
 
 
r   