a
    •˜ëj&7  ã                   @   sä   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 edœdd„ZG dd„ deeƒZG dd„ deƒZG dd„ deeƒZG dd„ deeƒZdS )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               
   C   sF   zddl } W n2 ty> } zd}t|ƒ|‚W Y d}~n
d}~0 0 | 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   ÚeÚmsg© r   úh/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/evaluation/string_distance/base.pyÚ_load_rapidfuzz   s    	ÿ r   c                   @   s(   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.
    Zdamerau_levenshteinZlevenshteinZjaroZjaro_winklerZhammingZindelN)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚDAMERAU_LEVENSHTEINÚLEVENSHTEINÚJAROÚJARO_WINKLERÚHAMMINGÚINDELr   r   r   r   r   (   s   r   c                   @   sÒ   e Zd ZU dZeejd�Zeed< edd�Z	e
ed< eeeef eeef dœdd„ƒZeee d	œd
d„ƒZeeef eeef dœdd„Zeddœee
edœdd„ƒZeed	œdd„ƒZeeedœdd„ZdS )Ú_RapidFuzzChainMixinz<Shared methods for the rapidfuzz string distance evaluators.)Údefaultr   TÚnormalize_score)Úvaluesr   c                 C   s
   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   )Úclsr(   r   r   r   Úvalidate_dependenciesD   s    
z*_RapidFuzzChainMixin.validate_dependenciesr   c                 C   s   dgS )zWGet the output keys.

        Returns:
            List[str]: The output keys.
        Úscorer   ©Úselfr   r   r   Úoutput_keysQ   s    z _RapidFuzzChainMixin.output_keys)Úresultr   c                 C   s(   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.
        r+   )r   Údict)r-   r/   r   r   r   Ú_prepare_outputZ   s    	z$_RapidFuzzChainMixin._prepare_outputF©r'   )r   r'   r   c                C   s|   ddl m} tj|jtj|jtj|jtj	|j
tj|jtj|ji}| |vrdd| › dttƒ› �}t|ƒ‚||  }|rv|jS |jS )aL  Get the distance metric function based on the distance type.

        Args:
            distance: The distance type.
            normalize_score: Whether to normalize the score.

        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   ZDamerauLevenshteinr    ZLevenshteinr!   ZJaror"   ZJaroWinklerr#   ZHammingr$   ZIndelÚlistÚ
ValueErrorZnormalized_distance)r   r'   Zrf_distanceZ
module_mapr   Úmoduler   r   r   Ú_get_metrich   s$    úÿÿz _RapidFuzzChainMixin._get_metricc                 C   s   t j| j| jd�S )zpGet the distance metric function.

        Returns:
            Callable: The distance metric function.
        r2   )r%   r6   r   r'   r,   r   r   r   Úmetric‹   s    þz_RapidFuzzChainMixin.metric)ÚaÚbr   c                 C   s   |   ||¡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.
        )r7   )r-   r8   r9   r   r   r   Úcompute_metric—   s    
z#_RapidFuzzChainMixin.compute_metricN)r   r   r   r   r
   r   r"   r   Ú__annotations__r'   Úboolr	   r0   Ústrr   r*   Úpropertyr3   r.   r1   Ústaticmethodr   r6   r7   Úfloatr:   r   r   r   r   r%   <   s   
" "r%   c                   @   sP  e Zd ZdZeedœdd„ƒZeedœdd„ƒZeee	 dœdd„ƒZ
ee	dœd	d
„ƒZedee	ef ee ee	ef dœdd„ƒZedee	ef ee ee	ef dœdd„ƒZedddddddœe	ee	 ee	 eeee	  eee	ef  eeedœ	dd„ƒZedddddddœe	ee	 ee	 eeee	  eee	ef  eeedœ	d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                 C   s   dS )z&This evaluator does not require input.Fr   r,   r   r   r   Úrequires_inputº   s    z&StringDistanceEvalChain.requires_inputc                 C   s   dS )z,This evaluator does not require a reference.Tr   r,   r   r   r   Úrequires_reference¿   s    z*StringDistanceEvalChain.requires_referencec                 C   s   ddgS )úUGet the input keys.

        Returns:
            List[str]: The input keys.
        Ú	referenceÚ
predictionr   r,   r   r   r   Ú
input_keysÄ   s    z"StringDistanceEvalChain.input_keysc                 C   s   | j j› d�S )úYGet the evaluation name.

        Returns:
            str: The evaluation name.
        Ú	_distance©r   Úvaluer,   r   r   r   Úevaluation_nameÍ   s    z'StringDistanceEvalChain.evaluation_nameN©ÚinputsÚrun_managerr   c                 C   s   d|   |d |d ¡iS ©aU  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.
        r+   rE   rF   ©r:   ©r-   rN   rO   r   r   r   Ú_callÖ   s    zStringDistanceEvalChain._callc                 Ã   s   d|   |d |d ¡iS rP   rQ   rR   r   r   r   Ú_acallè   s    zStringDistanceEvalChain._acallF)rE   ÚinputÚ	callbacksÚtagsÚmetadataÚinclude_run_info)	rF   rE   rU   rV   rW   rX   rY   Úkwargsr   c          
      K   s"   | ||dœ||||d�}	|   |	¡S )a$  Evaluate the string distance between the prediction and the reference.

        Args:
            prediction: The prediction string.
            reference: The reference string.
            input: The input string.
            callbacks: The callbacks to use.
            tags: The tags to apply.
            metadata: The metadata to use.
            include_run_info: Whether to include run info in the output.
            **kwargs: Additional keyword arguments.

        Returns:
            The evaluation results containing the score.
        ©rF   rE   ©rN   rV   rW   rX   rY   ©r1   ©
r-   rF   rE   rU   rV   rW   rX   rY   rZ   r/   r   r   r   Ú_evaluate_stringsú   s    ûz)StringDistanceEvalChain._evaluate_stringsc          
      Ë   s*   | j ||dœ||||d�I dH }	|  |	¡S )a&  Evaluate the string distance between the prediction and the reference.

        Args:
            prediction: The prediction string.
            reference: The reference string.
            input: The input string.
            callbacks: The callbacks to use.
            tags: The tags to apply.
            metadata: The metadata to apply.
            include_run_info: Whether to include run info in the output.
            **kwargs: Additional keyword arguments.

        Returns:
            The evaluation results containing the score.
        r[   r\   N©Zacallr1   r^   r   r   r   Ú_aevaluate_strings   s    ûz*StringDistanceEvalChain._aevaluate_strings)N)N)r   r   r   r   r>   r<   rB   rC   r3   r=   rG   rL   r   r0   r   r   r   rS   r   rT   r   r_   ra   r   r   r   r   rA   ¤   sv    ý

ü ý

ü÷
õ%÷
õrA   c                   @   s  e Zd ZdZeee dœdd„ƒZeedœdd„ƒZe	de
eef ee e
eef dœd	d
„ƒZe	de
eef ee e
eef dœdd„ƒZe	dddddœeeeeee  ee
eef  eee
dœdd„ƒZe	dddddœeeeeee  ee
eef  eee
dœdd„ƒZdS )ÚPairwiseStringDistanceEvalChainz6Compute string edit distances between two predictions.r   c                 C   s   ddgS )rD   rF   Úprediction_br   r,   r   r   r   rG   I  s    z*PairwiseStringDistanceEvalChain.input_keysc                 C   s   d| j j› d�S )rH   Z	pairwise_rI   rJ   r,   r   r   r   rL   R  s    z/PairwiseStringDistanceEvalChain.evaluation_nameNrM   c                 C   s   d|   |d |d ¡iS )aE  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.
        r+   rF   rc   rQ   rR   r   r   r   rS   [  s    ÿz%PairwiseStringDistanceEvalChain._callc                 Ã   s   d|   |d |d ¡iS )aY  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.
        r+   rF   rc   rQ   rR   r   r   r   rT   o  s    ÿz&PairwiseStringDistanceEvalChain._acallF)rV   rW   rX   rY   )rF   rc   rV   rW   rX   rY   rZ   r   c          	      K   s"   | ||dœ||||d�}|   |¡S )aÿ  Evaluate the string distance between two predictions.

        Args:
            prediction: The first prediction string.
            prediction_b: The second prediction string.
            callbacks: The callbacks to use.
            tags: The tags to apply.
            metadata: The metadata to use.
            include_run_info: Whether to include run info in the output.
            **kwargs: Additional keyword arguments.

        Returns:
            The evaluation results containing the score.
        ©rF   rc   r\   r]   ©	r-   rF   rc   rV   rW   rX   rY   rZ   r/   r   r   r   Ú_evaluate_string_pairsƒ  s    ûz6PairwiseStringDistanceEvalChain._evaluate_string_pairsc          	      Ë   s*   | j ||dœ||||d�I dH }|  |¡S )a  Asynchronously evaluate the string distance between two predictions.

        Args:
            prediction: The first prediction string.
            prediction_b: The second prediction string.
            callbacks: The callbacks to use.
            tags: The tags to apply.
            metadata: The metadata to use.
            include_run_info: Whether to include run info in the output.
            **kwargs: Additional keyword arguments.

        Returns:
            The evaluation results containing the score.
        rd   r\   Nr`   re   r   r   r   Ú_aevaluate_string_pairs¦  s    ûz7PairwiseStringDistanceEvalChain._aevaluate_string_pairs)N)N)r   r   r   r   r>   r3   r=   rG   rL   r   r0   r   r   r   rS   r   rT   r   r<   rf   rg   r   r   r   r   rb   F  sb    ý

ü ý

üø
ö"ø
örb   N)r   Úenumr   Útypingr   r   r   Zlangchain_core.callbacksr   Z langchain_core.callbacks.managerr   r   Zlangchain_core.utilsr	   Zpydanticr
   Ztyping_extensionsr   Zlangchain.chains.baser   Zlangchain.evaluation.schemar   r   Zlangchain.schemar   r   r=   r   r%   rA   rb   r   r   r   r   Ú<module>   s    h #