a
    dX                     @   s   d dl mZmZmZmZmZmZ d dlZd dl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mZ es~dgZG d	d
 d
eZdS )    )AnyListOptionalSequenceTupleUnionN)Tensortensor)_ter_compute_ter_update_TercomTokenizer)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPETranslationEditRate.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< dZe
ed	< eed
< eed< dZeee  ed< deeeeeedd fddZeeee f eeeee f  ddddZeeeeef f dddZdeeeee f  ee edddZ  ZS )TranslationEditRateat  Calculate Translation edit rate (`TER`_)  of machine translated text with one or more references.

    This implementation follows the one from `SacreBleu_ter`_, which is a
    near-exact reimplementation of the Tercom algorithm, produces identical results on all "sane" outputs.

    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:

    - ``ter`` (:class:`~torch.Tensor`): if ``return_sentence_level_score=True`` return a corpus-level translation
      edit rate with a list of sentence-level translation_edit_rate, else return a corpus-level translation edit rate

    Args:
        normalize: An indication whether a general tokenization to be applied.
        no_punctuation: An indication whteher a punctuation to be removed from the sentences.
        lowercase: An indication whether to enable case-insesitivity.
        asian_support: An indication whether asian characters to be processed.
        return_sentence_level_score: An indication whether a sentence-level TER to be returned.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.text import TranslationEditRate
        >>> preds = ['the cat is on the mat']
        >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
        >>> ter = TranslationEditRate()
        >>> ter(preds, target)
        tensor(0.1538)

    Fis_differentiablehigher_is_betterfull_state_update        plot_lower_boundg      ?plot_upper_boundtotal_num_editstotal_tgt_lenNsentence_terT)	normalizeno_punctuation	lowercaseasian_supportreturn_sentence_level_scorekwargsreturnc                    s   t  jf i | t|ts,td| dt|tsFtd| dt|ts`td| dt|tsztd| dt||||| _|| _| jdt	ddd	 | jd
t	ddd	 | jr| jdg dd	 d S )Nz<Expected argument `normalize` to be of type boolean but got .zAExpected argument `no_punctuation` to be of type boolean but got z<Expected argument `lowercase` to be of type boolean but got z@Expected argument `asian_support` to be of type boolean but got r   r   sum)Zdist_reduce_fxr   r   cat)
super__init__
isinstancebool
ValueErrorr   	tokenizerr    Z	add_stater	   )selfr   r   r   r   r    r!   	__class__ ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/text/ter.pyr'   I   s    	



zTranslationEditRate.__init__)predstargetr"   c                 C   s*   t ||| j| j| j| j\| _| _| _dS )z*Update state with predictions and targets.N)r   r+   r   r   r   )r,   r1   r2   r/   r/   r0   updated   s    zTranslationEditRate.update)r"   c                 C   s,   t | j| j}| jdur(|t| jfS |S )z)Calculate the translate error rate (TER).N)r
   r   r   r   torchr%   )r,   Zterr/   r/   r0   computeo   s    
zTranslationEditRate.compute)valaxr"   c                 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 TranslationEditRate
            >>> metric = TranslationEditRate()
            >>> preds = ['the cat is on the mat']
            >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torchmetrics.text import TranslationEditRate
            >>> metric = TranslationEditRate()
            >>> preds = ['the cat is on the mat']
            >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )Z_plot)r,   r6   r7   r/   r/   r0   plotv   s    *r   )FFTFF)NN)__name__
__module____qualname____doc__r   r)   __annotations__r   r   r   floatr   r   r   r   r   r   r'   r   strr   r3   r   r5   r   r   r8   __classcell__r/   r/   r-   r0   r      s<   
!     . r   )typingr   r   r   r   r   r   r4   r   r	   Z torchmetrics.functional.text.terr
   r   r   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__r   r/   r/   r/   r0   <module>   s    