
    Ng6                        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dS )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                  V    	 ddl } n# t          $ r t          d          w xY w| j        S )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    e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/evaluation/string_distance/base.py_load_rapidfuzzr      sS    
 
 
 
>
 
 	


 s    !c                   *    e Zd ZdZdZdZdZdZdZdZ	dS )	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   '   s9        	 	 0KD!LGEEEr,   r   c                   R   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dS )_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                 z    d|d         i}t           |v r'|t                                                    |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[   s;     6'?+f$Wo2244F7Or,   Fc                 d   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55555 .0N&(?!1')@"K$7 +"3&

 :%%<H < <%).%9%9< <   H% 	#--?"r,   c                 N    t                               | 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+     $//M4+? 0 
 
 	
r,   abc                 .    |                      ||          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F$u^-HIIIHnIII!E$///OT///J 4S> d38n    X T#Y    Xd38n c3h      #  #c  #D  #X  #  #  # \ #D 	
 	
 	
 	
 X	
! ! ! ! ! ! ! ! !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dS )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                     dS )z8
        This evaluator does not require input.
        Fr+   r7   s    r   requires_inputz&StringDistanceEvalChain.requires_input   s	    
 ur,   c                     dS )z>
        This evaluator does not require a reference.
        Tr+   r7   s    r   requires_referencez*StringDistanceEvalChain.requires_reference   s	    
 tr,   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                      | 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     -%0000r,   Ninputsrun_managerc                 J    d|                      |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WXXr,   c                 N   K   d|                      |d         |d                   iS )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WXXr,   F)r`   input	callbackstagsmetadatainclude_run_infora   r`   rq   rr   rs   rt   ru   kwargsc                R     | ||d||||          }	|                      |	          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   rr   rs   rt   ru   r=   
r8   ra   r`   rq   rr   rs   rt   ru   rv   r:   s
             r   _evaluate_stringsz)StringDistanceEvalChain._evaluate_strings  sG    2 ",9EE-
 
 
 ##F+++r,   c                v   K   |                      ||d||||           d{V }	|                     |	          S )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.
        rx   ry   Nacallr=   r{   s
             r   _aevaluate_stringsz*StringDistanceEvalChain._aevaluate_strings(  sk      4 zz",9EE- " 
 
 
 
 
 
 
 
 ##F+++r,   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        ,     X D    X +DI + + + X+ 1 1 1 1 X1 =AY YS#XY 89Y 
c3h	Y Y Y Y* BFY YS#XY =>Y 
c3h	Y Y Y Y. $(##$(-1!&!, !, !, !, C=	!,
 }!, !, tCy!!, 4S>*!, !, !, 
!, !, !, !,N $(##$(-1!&!, !, !, !, C=	!,
 }!, !, tCy!!, 4S>*!, !, !, 
!, !, !, !, !, !,r,   rY   c                      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dS )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                 "    d| j         j         dS )rd   	pairwise_re   rf   r7   s    r   rh   z/PairwiseStringDistanceEvalChain.evaluation_nameY  s     :4=.9999r,   Nri   rj   c                 J    d|                      |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V
 	
r,   c                 N   K   d|                      |d         |d                   iS )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  s1      " T(()=vn?UVV
 	
r,   F)rr   rs   rt   ru   ra   r   rr   rs   rt   ru   rv   c                R     | ||d||||          }|                      |          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   ry   rz   	r8   ra   r   rr   rs   rt   ru   rv   r:   s	            r   _evaluate_string_pairsz6PairwiseStringDistanceEvalChain._evaluate_string_pairs  sG    2 ",lKK-
 
 
 ##F+++r,   c                v   K   |                      ||d||||           d{V }|                     |          S )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   ry   Nr~   r   s	            r   _aevaluate_string_pairsz7PairwiseStringDistanceEvalChain._aevaluate_string_pairs  sk      2 zz",lK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  s2       @@.DI . . . X. : : : : X: =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      s   @ @       6 6 6 6 6 6 6 6 6 6 6 6 6 6         
 * ) ) ) ) )       ' ' ' ' ' ' P P P P P P P P $ $ $ $ $ $    (    S$   (i! i! i! i! i!5 i! i! i!Xb, b, b, b, b,o/C b, b, b,JA, A, A, A, A,&=?S A, A, A, A, A,r,   