
    ih6                         d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
mZmZ ddlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ d
efdZ G d dee      Z G d de      Z G d dee      Z G d dee      Zy)z:String distance evaluators based on the RapidFuzz library.    )Enum)AnyCallableDictListOptional)AsyncCallbackManagerForChainRunCallbackManagerForChainRun	Callbacks)pre_init)Field)Chain)PairwiseStringEvaluatorStringEvaluator)RUN_KEYreturnc                  T    	 ddl } | j                  S # t        $ r t        d      w xY w)z
    Load the RapidFuzz library.

    Raises:
        ImportError: If the rapidfuzz library is not installed.

    Returns:
        Any: The rapidfuzz.distance module.
    r   NzyPlease install the rapidfuzz library to use the FuzzyMatchStringEvaluator.Please install it with `pip install rapidfuzz`.)	rapidfuzzImportErrordistance)r   s    g/var/www/html/dev/engine/venv/lib/python3.12/site-packages/langchain/evaluation/string_distance/base.py_load_rapidfuzzr      s;    
   
>
 	

s    'c                   (    e Zd ZdZdZdZdZdZdZdZ	y)	StringDistancea7  Distance metric to use.

    Attributes:
        DAMERAU_LEVENSHTEIN: The Damerau-Levenshtein distance.
        LEVENSHTEIN: The Levenshtein distance.
        JARO: The Jaro distance.
        JARO_WINKLER: The Jaro-Winkler distance.
        HAMMING: The Hamming distance.
        INDEL: The Indel distance.
    damerau_levenshteinlevenshteinjarojaro_winklerhammingindelN)
__name__
__module____qualname____doc__DAMERAU_LEVENSHTEINLEVENSHTEINJAROJARO_WINKLERHAMMINGINDEL     r   r   r   '   s(    	 0KD!LGEr,   r   c                      e Zd ZU dZ eej                        Zeed<    ed      Z	e
ed<   	 edeeef   deeef   fd       Zedee   fd	       Zd
eeef   deeef   fdZeddede
defd       Zedefd       ZdededefdZy)_RapidFuzzChainMixinz<Shared methods for the rapidfuzz string distance evaluators.)defaultr   Tnormalize_scorevaluesr   c                     t                |S )z
        Validate that the rapidfuzz library is installed.

        Args:
            values (Dict[str, Any]): The input values.

        Returns:
            Dict[str, Any]: The validated values.
        )r   )clsr1   s     r   validate_dependenciesz*_RapidFuzzChainMixin.validate_dependenciesC   s     	r,   c                     dgS )z`
        Get the output keys.

        Returns:
            List[str]: The output keys.
        scorer+   selfs    r   output_keysz _RapidFuzzChainMixin.output_keysQ   s     yr,   resultc                 `    d|d   i}t         |v r|t            j                         |t         <   |S )z
        Prepare the output dictionary.

        Args:
            result (Dict[str, Any]): The evaluation results.

        Returns:
            Dict[str, Any]: The prepared output dictionary.
        r6   )r   dict)r8   r:   s     r   _prepare_outputz$_RapidFuzzChainMixin._prepare_output[   s5     6'?+f$Wo224F7Or,   c                    ddl m} t        j                  |j                  t        j
                  |j                  t        j                  |j                  t        j                  |j                  t        j                  |j                  t        j                  |j                  i}| |vrt        d|  dt!        t                     ||    }|r|j"                  S |j                  S )a  
        Get the distance metric function based on the distance type.

        Args:
            distance (str): The distance type.

        Returns:
            Callable: The distance metric function.

        Raises:
            ValueError: If the distance metric is invalid.
        r   )r   zInvalid distance metric: z
Must be one of: )r   r   r   r%   DamerauLevenshteinr&   Levenshteinr'   Jaror(   JaroWinklerr)   Hammingr*   Indel
ValueErrorlistnormalized_distance)r   r0   rf_distance
module_mapmodules        r   _get_metricz _RapidFuzzChainMixin._get_metricj   s     	6 ..0N0N&&(?(?!1!1'')@)@""K$7$7  +"3"3&

 :%+H:$T.%9$:<  H%---??"r,   c                 X    t         j                  | j                  | j                        S )zy
        Get the distance metric function.

        Returns:
            Callable: The distance metric function.
        )r0   )r.   rK   r   r0   r7   s    r   metricz_RapidFuzzChainMixin.metric   s+     $//MM4+?+? 0 
 	
r,   abc                 &    | j                  ||      S )z
        Compute the distance between two strings.

        Args:
            a (str): The first string.
            b (str): The second string.

        Returns:
            float: The distance between the two strings.
        )rM   )r8   rN   rO   s      r   compute_metricz#_RapidFuzzChainMixin.compute_metric   s     {{1a  r,   N)F)r!   r"   r#   r$   r   r   r(   r   __annotations__r0   boolr   r   strr   r4   propertyr   r9   r=   staticmethodr   rK   rM   floatrQ   r+   r,   r   r.   r.   ;   s   F$^-H-HIHnI!$/OT/J 4S> d38n   T#Y  d38n c3h   #c  #D  #X  #  #D 	
 	
 	
! ! ! !r,   r.   c                      e Zd ZdZedefd       Zedefd       Zedee	   fd       Z
ede	fd       Z	 ddee	ef   d	ee   dee	ef   fd
Z	 ddee	ef   d	ee   dee	ef   fdZdddddddde	dee	   dee	   dedeee	      deee	ef      dededefdZdddddddde	dee	   dee	   dedeee	      deee	ef      dededefdZy)StringDistanceEvalChainak  Compute string distances between the prediction and the reference.

    Examples
    ----------

    >>> from langchain.evaluation import StringDistanceEvalChain
    >>> evaluator = StringDistanceEvalChain()
    >>> evaluator.evaluate_strings(
            prediction="Mindy is the CTO",
            reference="Mindy is the CEO",
        )

    Using the `load_evaluator` function:

    >>> from langchain.evaluation import load_evaluator
    >>> evaluator = load_evaluator("string_distance")
    >>> evaluator.evaluate_strings(
            prediction="The answer is three",
            reference="three",
        )
    r   c                      y)z8
        This evaluator does not require input.
        Fr+   r7   s    r   requires_inputz&StringDistanceEvalChain.requires_input   s    
 r,   c                      y)z>
        This evaluator does not require a reference.
        Tr+   r7   s    r   requires_referencez*StringDistanceEvalChain.requires_reference   s    
 r,   c                 
    ddgS )^
        Get the input keys.

        Returns:
            List[str]: The input keys.
        	reference
predictionr+   r7   s    r   
input_keysz"StringDistanceEvalChain.input_keys   s     \**r,   c                 4    | j                   j                   dS )b
        Get the evaluation name.

        Returns:
            str: The evaluation name.
        	_distancer   valuer7   s    r   evaluation_namez'StringDistanceEvalChain.evaluation_name   s     --%%&i00r,   Ninputsrun_managerc                 6    d| j                  |d   |d         iS )a^  
        Compute the string distance between the prediction and the reference.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (Optional[CallbackManagerForChainRun]):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r6   r`   ra   rQ   r8   ri   rj   s      r   _callzStringDistanceEvalChain._call   s&      ,,VK-@&BVWXXr,   c                 >   K   d| j                  |d   |d         iS w)a}  
        Asynchronously compute the string distance between the prediction
            and the reference.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (Optional[AsyncCallbackManagerForChainRun]:
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r6   r`   ra   rl   rm   s      r   _acallzStringDistanceEvalChain._acall   s*     " ,,VK-@&BVWXX   F)r`   input	callbackstagsmetadatainclude_run_infora   r`   rr   rs   rt   ru   rv   kwargsc                D     | ||d||||      }	| j                  |	      S )a  
        Evaluate the string distance between the prediction and the reference.

        Args:
            prediction (str): The prediction string.
            reference (Optional[str], optional): The reference string.
            input (Optional[str], optional): The input string.
            callbacks (Callbacks, optional): The callbacks to use.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        ra   r`   ri   rs   rt   ru   rv   r=   
r8   ra   r`   rr   rs   rt   ru   rv   rw   r:   s
             r   _evaluate_stringsz)StringDistanceEvalChain._evaluate_strings  s5    2 ",9E-
 ##F++r,   c                r   K   | j                  ||d||||       d{   }	| j                  |	      S 7 w)a  
        Asynchronously evaluate the string distance between the
            prediction and the reference.

        Args:
            prediction (str): The prediction string.
            reference (Optional[str], optional): The reference string.
            input (Optional[str], optional): The input string.
            callbacks (Callbacks, optional): The callbacks to use.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        ry   rz   Nacallr=   r|   s
             r   _aevaluate_stringsz*StringDistanceEvalChain._aevaluate_strings(  sL     4 zz",9E- " 
 
 ##F++
   757N)r!   r"   r#   r$   rU   rS   r[   r]   r   rT   rb   rh   r   r   r   r
   rn   r	   rp   r   r<   r}   r   r+   r,   r   rY   rY      s   ,    D   +DI + + 1 1 1 =AYS#XY 89Y 
c3h	Y* BFYS#XY =>Y 
c3h	Y. $(##$(-1!&!, !, C=	!,
 }!, !, tCy!!, 4S>*!, !, !, 
!,N $(##$(-1!&!, !, C=	!,
 }!, !, tCy!!, 4S>*!, !, !, 
!,r,   rY   c                   F   e Zd ZdZedee   fd       Zedefd       Z	 dde	ee
f   dee   de	ee
f   fdZ	 dde	ee
f   dee   de	ee
f   fd	Zdddd
ddedededeee      dee	ee
f      dede
defdZdddd
ddedededeee      dee	ee
f      dede
defdZy)PairwiseStringDistanceEvalChainz6Compute string edit distances between two predictions.r   c                 
    ddgS )r_   ra   prediction_br+   r7   s    r   rb   z*PairwiseStringDistanceEvalChain.input_keysO  s     n--r,   c                 6    d| j                   j                   dS )rd   	pairwise_re   rf   r7   s    r   rh   z/PairwiseStringDistanceEvalChain.evaluation_nameY  s     4==../y99r,   Nri   rj   c                 6    d| j                  |d   |d         iS )aN  
        Compute the string distance between two predictions.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (CallbackManagerForChainRun , optional):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r6   ra   r   rl   rm   s      r   rn   z%PairwiseStringDistanceEvalChain._callc  s*    " T(()=vn?UV
 	
r,   c                 >   K   d| j                  |d   |d         iS w)ab  
        Asynchronously compute the string distance between two predictions.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (AsyncCallbackManagerForChainRun , optional):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r6   ra   r   rl   rm   s      r   rp   z&PairwiseStringDistanceEvalChain._acallw  s.     " T(()=vn?UV
 	
rq   F)rs   rt   ru   rv   ra   r   rs   rt   ru   rv   rw   c                D     | ||d||||      }| j                  |      S )a$  
        Evaluate the string distance between two predictions.

        Args:
            prediction (str): The first prediction string.
            prediction_b (str): The second prediction string.
            callbacks (Callbacks, optional): The callbacks to use.
            tags (List[str], optional): Tags to apply to traces.
            metadata (Dict[str, Any], optional): Metadata to apply to traces.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        ra   r   rz   r{   	r8   ra   r   rs   rt   ru   rv   rw   r:   s	            r   _evaluate_string_pairsz6PairwiseStringDistanceEvalChain._evaluate_string_pairs  s5    2 ",lK-
 ##F++r,   c                r   K   | j                  ||d||||       d{   }| j                  |      S 7 w)a3  
        Asynchronously evaluate the string distance between two predictions.

        Args:
            prediction (str): The first prediction string.
            prediction_b (str): The second prediction string.
            callbacks (Callbacks, optional): The callbacks to use.
            tags (List[str], optional): Tags to apply to traces.
            metadata (Dict[str, Any], optional): Metadata to apply to traces.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        r   rz   Nr   r   s	            r   _aevaluate_string_pairsz7PairwiseStringDistanceEvalChain._aevaluate_string_pairs  sL     2 zz",lK- " 
 
 ##F++
r   r   )r!   r"   r#   r$   rU   r   rT   rb   rh   r   r   r   r
   rn   r	   rp   r   rS   r<   r   r   r+   r,   r   r   r   L  s   @.DI . . : : : =A
S#X
 89
 
c3h	
. BF
S#X
 =>
 
c3h	
2  $$(-1!& ,  , 	 ,
  , tCy! , 4S>* ,  ,  , 
 ,N  $$(-1!& ,  , 	 ,
  , tCy! , 4S>* ,  ,  , 
 ,r,   r   N)r$   enumr   typingr   r   r   r   r    langchain_core.callbacks.managerr	   r
   r   langchain_core.utilsr   pydanticr   langchain.chains.baser   langchain.evaluation.schemar   r   langchain.schemar   r   rT   r   r.   rY   r   r+   r,   r   <module>r      sy    @  6 6 
 *  ' P $ (S$ (i!5 i!Xb,o/C b,JA,&=?S A,r,   