o
    §ôjú(  ã                	   @   sò   d dl Z d dlmZ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 d dlmZmZmZ d dlmZ d dlmZmZ esGd	gZd
ZdZdZeeee
f eee
f eee
f eee
f eee
f eee
f f ZG dd„ deƒZdS )é    N)ÚIteratorÚSequence)ÚAnyÚListÚOptionalÚUnion)ÚTensorÚtensor)ÚMetric)Ú_chrf_score_computeÚ_chrf_score_updateÚ_prepare_n_grams_dicts)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúCHRFScore.plot)ÚcharÚword)ÚpredsÚtargetÚmatching)Útotal_preds_char_n_gramsÚtotal_preds_word_n_gramsÚtotal_target_char_n_gramsÚtotal_target_word_n_gramsÚtotal_matching_char_n_gramsÚtotal_matching_word_n_gramsc                       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
< dZeee  ed< 						d2dedede
dededededdf‡ fdd„Zdee deee  ddfdd„Zdeeeeef f fdd„Zdefd d!„Zd"eddfd#d$„Zed%ed&edefd'd(„ƒZed%ed&ed)edefd*d+„ƒZdeeeeef ef  fd,d-„Z 	d3d.eeeee f  d/ee! de"fd0d1„Z#‡  Z$S )4Ú	CHRFScoreaÈ  Calculate `chrf score`_ of machine translated text with one or more references.

    This implementation supports both ChrF score computation introduced in `chrF score`_ and `chrF++ score`_ introduced
    in `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and
    https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py.

    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:

    - ``chrf`` (:class:`~torch.Tensor`): If `return_sentence_level_score=True` return a list of sentence-level
      chrF/chrF++ scores, else return a corpus-level chrF/chrF++ score

    Args:
        n_char_order: A character n-gram order. If ``n_char_order=6``, the metrics refers to the official chrF/chrF++.
        n_word_order: A word n-gram order. If ``n_word_order=2``, the metric refers to the official chrF++.
            If ``n_word_order=0``, the metric is equivalent to the original ChrF.
        beta: parameter determining an importance of recall w.r.t. precision. If ``beta=1``, their importance is equal.
        lowercase: An indication whether to enable case-insensitivity.
        whitespace: An indication whether keep whitespaces during n-gram extraction.
        return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``n_char_order`` is not an integer greater than or equal to 1.
        ValueError:
            If ``n_word_order`` is not an integer greater than or equal to 0.
        ValueError:
            If ``beta`` is smaller than 0.

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

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateç        Úplot_lower_boundg      ð?Úplot_upper_boundNÚsentence_chrf_scoreé   é   ç       @Ún_char_orderÚn_word_orderÚbetaÚ	lowercaseÚ
whitespaceÚreturn_sentence_level_scoreÚkwargsÚreturnc                    sò   t ƒ jdi |¤Ž t|tƒr|dk rtdƒ‚|| _t|tƒr"|dk r&tdƒ‚|| _|dk r1tdƒ‚|| _|| _|| _	|| _
t|| ƒ| _|  ¡ D ]!\\}}	}
td|	d ƒD ]}|  |
||¡}| j|tdƒdd� qUqH| j
rw| jd	g d
d� d S d S )Né   zMExpected argument `n_char_order` to be an integer greater than or equal to 1.r   zMExpected argument `n_word_order` to be an integer greater than or equal to 0.z.Expected argument `beta` to be greater than 0.r!   Úsum)Údist_reduce_fxr$   Úcat© )ÚsuperÚ__init__Ú
isinstanceÚintÚ
ValueErrorr(   r)   r*   r+   r,   r-   ÚfloatÚn_orderÚ_get_text_n_gram_iteratorÚrangeÚ_get_state_nameÚ	add_stater	   )Úselfr(   r)   r*   r+   r,   r-   r.   Ún_gram_levelÚn_gram_orderÚtextÚnÚ
state_name©Ú	__class__r4   úi/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/text/chrf.pyr6   j   s,   
þÿzCHRFScore.__init__r   r   c                 C   sx   t ||g|  ¡ ¢| j‘| j‘| j‘| j‘| j‘| j‘| jr | j	nd‘R Ž }|  
|dd… ¡ | j	dur:|d | _	dS dS )z*Update state with predictions and targets.Néÿÿÿÿ)r   Ú_convert_states_to_dictsr(   r)   r;   r*   r+   r,   r-   r$   Ú_update_states_from_dicts)r@   r   r   Ún_grams_dicts_tupler4   r4   rH   ÚupdateŽ   s0   þýüûúùø	÷
ö
ÿzCHRFScore.updatec                 C   sR   | j durtg |  ¡ ¢| j‘| j‘R Ž t | j ¡fS tg |  ¡ ¢| j‘| j‘R Ž S )zCalculate chrF/chrF++ score.N)r$   r   rJ   r;   r*   Útorchr3   ©r@   r4   r4   rH   Úcompute    s
   

þzCHRFScore.computec                 C   sz   t ttt| j| jƒƒƒ}|  ¡ D ]&\\}}}td|d ƒD ]}|  ||¡}|  	|||¡}t
| |ƒ|| |< qqt| ¡ ƒS )z_Convert global metric states to the n-gram dictionaries to be passed in ``_chrf_score_update``.r0   )ÚdictÚzipÚ_DICT_STATES_NAMESr   r(   r)   r<   r=   Ú_get_dict_namer>   ÚgetattrÚtupleÚvalues)r@   Ún_grams_dictsrA   rB   rC   rD   Ú	dict_namerE   r4   r4   rH   rJ   ©   s   ÿüz"CHRFScore._convert_states_to_dictsrL   c           	      C   sj   t tt|ƒƒ}|  ¡ D ]'\\}}}td|d ƒD ]}|  ||¡}|  |||¡}t| ||| | ƒ qqdS )z]Update global metric states based on the n-gram dictionaries calculated on the current batch.r0   N)rQ   rR   rS   r<   r=   rT   r>   Úsetattr)	r@   rL   rX   rA   rB   rC   rD   rY   rE   r4   r4   rH   rK   ¸   s   üÿz#CHRFScore._update_states_from_dictsrC   rA   c                 C   s   d| › d|› d�S )z*Return a dictionary name w.r.t input args.Útotal_Ú_Z_n_gramsr4   )rC   rA   r4   r4   rH   rT   Â   s   zCHRFScore._get_dict_namerD   c                 C   s   d| › d|› d|› d�S )z,Return a metric state name w.r.t input args.r[   r\   Z_gramsr4   )rC   rA   rD   r4   r4   rH   r>   Ç   s   zCHRFScore._get_state_namec                 C   s   t  tt| j| jgƒt¡S )zKGet iterator over char/word and reference/hypothesis/matching n-gram level.)Ú	itertoolsÚproductrR   Ú_N_GRAM_LEVELSr(   r)   Ú_TEXT_LEVELSrO   r4   r4   rH   r<   Ì   s   z#CHRFScore._get_text_n_gram_iteratorÚ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 CHRFScore
            >>> metric = CHRFScore()
            >>> 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 CHRFScore
            >>> metric = CHRFScore()
            >>> 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@   ra   rb   r4   r4   rH   ÚplotÐ   s   *r   )r%   r&   r'   FFF)NN)%Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r    r"   r:   r#   r$   r   r   r   r8   r   r6   r   ÚstrrM   r   rV   rP   Ú_DICT_STATES_TYPESrJ   rK   ÚstaticmethodrT   r>   r   r<   r   r   rd   Ú__classcell__r4   r4   rF   rH   r   5   s`   
 ,ùþýüûúùø	÷"$	
"ÿÿÿþr   ) r]   Úcollections.abcr   r   Útypingr   r   r   r   rN   r   r	   Útorchmetricsr
   Ú!torchmetrics.functional.text.chrfr   r   r   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r_   r`   rS   rV   rQ   r8   rl   r   r4   r4   r4   rH   Ú<module>   s$   	>ÿ