
    hL7                         d Z ddlmZ ddlmZmZmZ ddlmZ ddl	m
Z
mZ ddl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Optional)	Callbacks)AsyncCallbackManagerForChainRunCallbackManagerForChainRun)pre_init)Field)override)Chain)PairwiseStringEvaluatorStringEvaluator)RUN_KEYreturnc                  b    	 ddl } | j                  S # t        $ r}d}t        |      |d}~w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   emsgs      g/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain/evaluation/string_distance/base.py_load_rapidfuzzr      sC    &   &> 	 #A%&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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   )clsr2   s     r   validate_dependenciesz*_RapidFuzzChainMixin.validate_dependenciesE   s     	r-   c                     dgS )z`
        Get the output keys.

        Returns:
            List[str]: The output keys.
        scorer,   selfs    r   output_keysz _RapidFuzzChainMixin.output_keysS   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.
        r7   )r   dict)r9   r;   s     r   _prepare_outputz$_RapidFuzzChainMixin._prepare_output]   s5     6'?+f$Wo224F7Or-   Fr1   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 d|  dt        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list
ValueErrornormalized_distance)r   r1   rf_distance
module_mapr   modules         r   _get_metricz _RapidFuzzChainMixin._get_metricl   s     	6 ..0N0N&&(?(?!1!1'')@)@""K$7$7  +"3"3&

 :%+H:$T.%9$:<  S/!H%---r-   c                 X    t         j                  | j                  | j                        S )zy
        Get the distance metric function.

        Returns:
            Callable: The distance metric function.
        r?   )r/   rM   r   r1   r8   s    r   metricz_RapidFuzzChainMixin.metric   s,     $//MM 00 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.
        )rO   )r9   rP   rQ   s      r   compute_metricz#_RapidFuzzChainMixin.compute_metric   s     {{1a  r-   N)r"   r#   r$   r%   r   r   r)   r   __annotations__r1   boolr
   r=   strr   r5   propertyrG   r:   r>   staticmethodr   rM   rO   floatrS   r,   r-   r   r/   r/   =   s   F$^-H-HIHnI!$/OT/J 4S> d38n   T#Y  d38n c3h  >C  c  t      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e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e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,   r8   s    r   requires_inputz&StringDistanceEvalChain.requires_input   s    
 r-   c                      y)z>
        This evaluator does not require a reference.
        Tr,   r8   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,   r8   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   valuer8   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.
        r7   rb   rc   rS   r9   rk   rl   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.
        r7   rb   rc   rn   ro   s      r   _acallzStringDistanceEvalChain._acall   s*     " ,,VK-@&BVWXX   F)rb   input	callbackstagsmetadatainclude_run_inforc   rb   rt   ru   rv   rw   rx   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.
        rc   rb   rk   ru   rv   rw   rx   r>   
r9   rc   rb   rt   ru   rv   rw   rx   ry   r;   s
             r   _evaluate_stringsz)StringDistanceEvalChain._evaluate_strings  s5    4 ",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.
        r{   r|   Nacallr>   r~   s
             r   _aevaluate_stringsz*StringDistanceEvalChain._aevaluate_strings,  sL     6 zz",9E- " 
 
 ##F++
   757N)r"   r#   r$   r%   rW   rU   r]   r_   rG   rV   rd   rj   r=   r   r   r	   rp   r   rr   r   r   r   r   r,   r-   r   r[   r[      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>*!, !, !, 
!, !,F 
 $(##$(-1!&!, !, C=	!,
 }!, !, tCy!!, 4S>*!, !, !, 
!, !,r-   r[   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 )ra   rc   prediction_br,   r8   s    r   rd   z*PairwiseStringDistanceEvalChain.input_keysT  s     n--r-   c                 6    d| j                   j                   dS )rf   	pairwise_rg   rh   r8   s    r   rj   z/PairwiseStringDistanceEvalChain.evaluation_name^  s     4==../y99r-   Nrk   rl   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.
        r7   rc   r   rn   ro   s      r   rp   z%PairwiseStringDistanceEvalChain._callh  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.
        r7   rc   r   rn   ro   s      r   rr   z&PairwiseStringDistanceEvalChain._acall|  s.     " T(()=vn?UV
 	
rs   F)ru   rv   rw   rx   rc   r   ru   rv   rw   rx   ry   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.
        rc   r   r|   r}   	r9   rc   r   ru   rv   rw   rx   ry   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   r|   Nr   r   s	            r   _aevaluate_string_pairsz7PairwiseStringDistanceEvalChain._aevaluate_string_pairs  sL     2 zz",lK- " 
 
 ##F++
r   r   )r"   r#   r$   r%   rW   rG   rV   rd   rj   r=   r   r   r	   rp   r   rr   r   rU   r   r   r,   r-   r   r   r   Q  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   langchain_core.callbacksr    langchain_core.callbacks.managerr   r	   langchain_core.utilsr
   pydanticr   typing_extensionsr   langchain.chains.baser   langchain.evaluation.schemar   r   langchain.schemar   r   rV   r   r/   r[   r   r,   r-   r   <module>r      sz    @  * * . *  & ' P $ *S$ (j!5 j!Zd,o/C d,NA,&=?S A,r-   