o
    ªôjm  ã                   @   s–   d dl mZ d dl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sAd	gZG d
d„ deƒZdS )é    )ÚSequence)ÚAnyÚListÚOptionalÚ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"dededededededdf‡ fdd„Zdeeee f deeeee f  ddfdd„Zdeeeeef f fdd„Z	d#deeeee f  dee defd d!„Z‡  ZS )$ÚTranslationEditRateau  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-insensitivity.
        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di |¤Ž t|tƒstd|› d�ƒ‚t|tƒs#td|› d�ƒ‚t|tƒs0td|› d�ƒ‚t|tƒs=td|› d�ƒ‚t||||ƒ| _|| _| jdt	dƒdd	� | jd
t	dƒdd	� | jri| jdg dd	� d S 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)Údist_reduce_fxr   r   Úcat© )
ÚsuperÚ__init__Ú
isinstanceÚboolÚ
ValueErrorr   Ú	tokenizerr   Ú	add_stater   )Úselfr   r   r   r   r   r    ©Ú	__class__r&   úh/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/text/ter.pyr(   J   s    	



ÿzTranslationEditRate.__init__ÚpredsÚtargetc                 C   s*   t ||| j| j| j| jƒ\| _| _| _dS )z*Update state with predictions and targets.N)r
   r,   r   r   r   )r.   r2   r3   r&   r&   r1   Úupdatee   s   úzTranslationEditRate.updatec                 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.   Úterr&   r&   r1   Úcomputep   s   
zTranslationEditRate.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 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)

        )Ú_plot)r.   r8   r9   r&   r&   r1   Úplotw   s   *r   )FFTFF)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r*   Ú__annotations__r   r   r   Úfloatr   r   r   r   r   r   r(   r   Ústrr   r4   Útupler7   r   r   r;   Ú__classcell__r&   r&   r/   r1   r      sP   
 !úþýüûúùø2ÿÿÿþr   )Úcollections.abcr   Útypingr   r   r   r   r5   r   r   Ú torchmetrics.functional.text.terr	   r
   r   Útorchmetrics.metricr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r&   r&   r&   r1   Ú<module>   s   