
    h                     ^    d dl Z d dlmZmZmZmZ d dlmZ d dlm	Z	 d dl
mZ  G d de      Zy)    N)AnyCallableOptionalUnion)parse_json_markdown)override)StringEvaluatorc                        e Zd ZdZ	 	 ddeeeegef      deeegef      deddf fdZ	e
defd       Ze
defd	       Ze
defd
       Zdedeeedeeeef   fdZe	 	 ddedee   dee   dedef
d       Z xZS )JsonEditDistanceEvaluatora  
    An evaluator that calculates the edit distance between JSON strings.

    This evaluator computes a normalized Damerau-Levenshtein distance between two JSON strings
    after parsing them and converting them to a canonical format (i.e., whitespace and key order are normalized).
    It can be customized with alternative distance and canonicalization functions.

    Args:
        string_distance (Optional[Callable[[str, str], float]]): A callable that computes the distance between two strings.
            If not provided, a Damerau-Levenshtein distance from the `rapidfuzz` package will be used.
        canonicalize (Optional[Callable[[Any], Any]]): A callable that converts a parsed JSON object into its canonical string form.
            If not provided, the default behavior is to serialize the JSON with sorted keys and no extra whitespace.
        **kwargs (Any): Additional keyword arguments.

    Attributes:
        _string_distance (Callable[[str, str], float]): The internal distance computation function.
        _canonicalize (Callable[[Any], Any]): The internal canonicalization function.

    Examples:
        >>> evaluator = JsonEditDistanceEvaluator()
        >>> result = evaluator.evaluate_strings(prediction='{"a": 1, "b": 2}', reference='{"a": 1, "b": 3}')
        >>> assert result["score"] is not None

    Raises:
        ImportError: If `rapidfuzz` is not installed and no alternative `string_distance` function is provided.

    Nstring_distancecanonicalizekwargsreturnc                     t         |           ||| _        n"	 ddlm} |j                  j                  | _        ||| _        y d | _        y # t
        $ r}d}t        |      |d }~ww xY w)Nr   )distancezThe default string_distance operator for the  JsonEditDistanceEvaluator requires installation of the rapidfuzz package. Please install it with `pip install rapidfuzz`.c                 2    t        j                  | dd      S )N),:T)
separators	sort_keys)jsondumps)xs    h/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain/evaluation/parsing/json_distance.py<lambda>z4JsonEditDistanceEvaluator.__init__.<locals>.<lambda>?   s    4::%,     )	super__init___string_distance	rapidfuzzr   ImportErrorDamerauLevenshteinnormalized_distance_canonicalize)selfr   r   r   rfdemsg	__class__s          r   r   z"JsonEditDistanceEvaluator.__init__'   s     	&$3D!	.5 %($:$:$N$ND!#!-D"D  .F  "#&A-.s   A 	A+A&&A+c                      y)NF r%   s    r   requires_inputz(JsonEditDistanceEvaluator.requires_inputE   s    r   c                      y)NTr+   r,   s    r   requires_referencez,JsonEditDistanceEvaluator.requires_referenceI   s    r   c                      y)Njson_edit_distancer+   r,   s    r   evaluation_namez)JsonEditDistanceEvaluator.evaluation_nameM   s    #r   nodec                 <    t        |t              rt        |      S |S )N)
isinstancestrr   )r%   r3   s     r   _parse_jsonz%JsonEditDistanceEvaluator._parse_jsonQ   s    dC &t,,r   
predictioninput	referencec                     | j                  | j                  |            }| j                  | j                  |            }| j                  ||      }d|iS )Nscore)r$   r7   r   )r%   r8   r9   r:   r   parsedlabelr   s           r   _evaluate_stringsz+JsonEditDistanceEvaluator._evaluate_stringsV   sW     ##D$4$4Z$@A""4#3#3I#>?((7""r   )NN)__name__
__module____qualname____doc__r   r   r6   floatr   r   propertyboolr-   r/   r2   r   dictlistintr7   r   r?   __classcell__)r)   s   @r   r   r   
   s-   < BF7;!(C:u+<"=> xs
34 	
 
<    D   $ $ $ dD$tSRU.U(V 
   $#'	
#
# }
# C=	
#
 
# 

# 
#r   r   )r   typingr   r   r   r   langchain_core.utils.jsonr   typing_extensionsr   langchain.evaluation.schemar	   r   r+   r   r   <module>rO      s%     1 1 9 & 7W# W#r   