o
    .wi                     @   s   d dl mZ d dlmZmZmZmZmZ d dl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mZ esEd
gZG dd deZdS )    )Sequence)AnyListLiteralOptionalUnionN)Tensor)_edit_distance_compute_edit_distance_update)Metric)dim_zero_cat)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEEditDistance.plotc                	       s   e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< ee ed< eed	< eed
< 	ddedeed  deddf fddZdeeee f deeee f ddfddZdejfddZ	d deeeee f  dee defddZ  ZS )!EditDistanceu	  Calculates the Levenshtein edit distance between two sequences.

    The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the
    predicted text into the reference text. The lower the distance, the more accurate the model is considered to be.

    Implementation is similar to `nltk.edit_distance <https://www.nltk.org/_modules/nltk/metrics/distance.html>`_.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus
    - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus

    As output of ``forward`` and ``compute`` the metric returns the following output:

    - ``eed`` (:class:`~torch.Tensor`): A tensor with the extended edit distance score. If `reduction` is set to
      ``'none'`` or ``None``, this has shape ``(N, )``, where ``N`` is the batch size. Otherwise, this is a scalar.

    Args:
        substitution_cost: The cost of substituting one character for another.
        reduction: a method to reduce metric score over samples.

            - ``'mean'``: takes the mean over samples
            - ``'sum'``: takes the sum over samples
            - ``None`` or ``'none'``: return the score per sample

        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example::
        Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits:

        >>> from torchmetrics.text import EditDistance
        >>> metric = EditDistance()
        >>> metric(["rain"], ["shine"])
        tensor(3.)

    Example::
        Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine”
        takes 3 edits, where two of them are substitutions:

        >>> from torchmetrics.text import EditDistance
        >>> metric = EditDistance(substitution_cost=2)
        >>> metric(["rain"], ["shine"])
        tensor(5.)

    Example::
        Multiple strings example:

        >>> from torchmetrics.text import EditDistance
        >>> metric = EditDistance(reduction=None)
        >>> metric(["rain", "lnaguaeg"], ["shine", "language"])
        tensor([3, 4], dtype=torch.int32)
        >>> metric = EditDistance(reduction="mean")
        >>> metric(["rain", "lnaguaeg"], ["shine", "language"])
        tensor(3.5000)

    Fhigher_is_betteris_differentiablefull_state_updateg        plot_lower_boundedit_scores_listedit_scoresnum_elements   meansubstitution_cost	reduction)r   sumnonekwargsreturnNc                    s   t  jdi | t|tr|dkstd| || _d}||vr,td| d| || _| jdks9| jd u rC| jdg dd	 d S | jd
t	ddd	 | jdt	ddd	 d S )Nr   zHExpected argument `substitution_cost` to be a positive integer, but got )Nr   r   r   z+Expected argument `reduction` to be one of z
, but got r   r   cat)defaultdist_reduce_fxr   r   r    )
super__init__
isinstanceint
ValueErrorr   r   	add_statetorchtensor)selfr   r   r   allowed_reduction	__class__r$   S/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/text/edit.pyr&   a   s   zEditDistance.__init__predstargetc                 C   s\   t ||| j}| jdks| jdu r| j| dS |  j| 7  _|  j|jd 7  _dS )z*Update state with predictions and targets.r   Nr   )	r
   r   r   r   appendr   r   r   shape)r-   r2   r3   distancer$   r$   r1   updatev   s
   zEditDistance.updatec                 C   s:   | j dks
| j du rtt| jd| j S t| j| j| j S )z%Compute the edit distance over state.r   Nr   )r   r	   r   r   r   r   )r-   r$   r$   r1   compute   s   zEditDistance.computevalaxc                 C   s   |  ||S )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> from torchmetrics.text import EditDistance
            >>> metric = EditDistance()
            >>> preds = ["this is the prediction", "there is an other sample"]
            >>> target = ["this is the reference", "there is another one"]
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torchmetrics.text import EditDistance
            >>> metric = EditDistance()
            >>> preds = ["this is the prediction", "there is an other sample"]
            >>> target = ["this is the reference", "there is another one"]
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r-   r9   r:   r$   r$   r1   plot   s   *r   )r   r   )NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   r(   r   r   r   r&   r   strr   r7   r+   r8   r   r   r<   __classcell__r$   r$   r/   r1   r      s:   
 9
.	r   )collections.abcr   typingr   r   r   r   r   r+   r   !torchmetrics.functional.text.editr	   r
   torchmetrics.metricr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r$   r$   r$   r1   <module>   s   