o
    ¨ôjÄ$  ã                   @   s¨   d dl m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 d dlmZmZmZmZ d dlmZmZ d dlmZmZ esEd	gZd
dgiZG dd„ deƒZdS )é    )ÚSequence)ÚAnyÚCallableÚOptionalÚUnion)ÚTensor)ÚLiteral)ÚMetric)ÚALLOWED_ACCUMULATE_VALUESÚALLOWED_ROUGE_KEYSÚ_rouge_score_computeÚ_rouge_score_update)Ú_MATPLOTLIB_AVAILABLEÚ_NLTK_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúROUGEScore.plot)Ú
ROUGEScoreÚnltkc                       sF  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%dedeeegef  deeegee f  ded deeeedf f deddf‡ fdd„Zdeeee f deeee eee  f ddfdd„Zdeeef fdd„Zdefdd „Z	d&d!eeeee f  d"ee defd#d$„Z‡  ZS )'r   a¯
  `Calculate Rouge Score`_, used for automatic summarization.

    This implementation should imitate the behaviour of the ``rouge-score`` package `Python ROUGE Implementation`

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

    - ``preds`` (:class:`~Sequence`): An iterable of predicted sentences or a single predicted sentence
    - ``target`` (:class:`~Sequence`): An iterable of target sentences
      or an iterable of interables of target sentences
      or a single target sentence

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

    - ``rouge`` (:class:`~Dict`): A dictionary of tensor rouge scores for each input str rouge key

    Args:
        use_stemmer: Use Porter stemmer to strip word suffixes to improve matching.
        normalizer: A user's own normalizer function.
            If this is ``None``, replacing any non-alpha-numeric characters with spaces is default.
            This function must take a ``str`` and return a ``str``.
        tokenizer:
            A user's own tokenizer function. If this is ``None``, splitting by spaces is default
            This function must take a ``str`` and return ``Sequence[str]``
        accumulate:
            Useful in case of multi-reference rouge score.

            - ``avg`` takes the avg of all references with respect to predictions
            - ``best`` takes the best fmeasure score obtained between prediction and multiple corresponding references.

        rouge_keys: A list of rouge types to calculate.
            Keys that are allowed are ``rougeL``, ``rougeLsum``, and ``rouge1`` through ``rouge9``.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.text.rouge import ROUGEScore
        >>> preds = "My name is John"
        >>> target = "Is your name John"
        >>> rouge = ROUGEScore()
        >>> from pprint import pprint
        >>> pprint(rouge(preds, target))
        {'rouge1_fmeasure': tensor(0.7500),
         'rouge1_precision': tensor(0.7500),
         'rouge1_recall': tensor(0.7500),
         'rouge2_fmeasure': tensor(0.),
         'rouge2_precision': tensor(0.),
         'rouge2_recall': tensor(0.),
         'rougeL_fmeasure': tensor(0.5000),
         'rougeL_precision': tensor(0.5000),
         'rougeL_recall': tensor(0.5000),
         'rougeLsum_fmeasure': tensor(0.5000),
         'rougeLsum_precision': tensor(0.5000),
         'rougeLsum_recall': tensor(0.5000)}


    Raises:
        ValueError:
            If the python packages ``nltk`` is not installed.
        ValueError:
            If any of the ``rouge_keys`` does not belong to the allowed set of keys.

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateg        Úplot_lower_boundg      ð?Úplot_upper_boundNÚbest©Úrouge1Úrouge2ÚrougeLÚ	rougeLsumÚuse_stemmerÚ
normalizerÚ	tokenizerÚ
accumulate)Úavgr   Ú
rouge_keys.ÚkwargsÚreturnc                    sö   t ƒ jdi |¤Ž |sd|v rtstdƒ‚dd l}t|tƒs!|f}|D ]}|tvr3td|› dt› �ƒ‚q#|t	vrBtd|› dt	› �ƒ‚|| _
dd„ |D ƒ| _|rU|jj ¡ nd | _|| _|| _|| _| j
D ]}	d	D ]}
| j|	› d
|
› �g d d� qhqdd S )Nr   zUStemmer and/or `rougeLsum` requires that `nltk` is installed. Use `pip install nltk`.r   zGot unknown rouge key z. Expected to be one of zGot unknown accumulate value c                 S   s   g | ]}t | ‘qS © )r   )Ú.0Úkeyr(   r(   új/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/text/rouge.pyÚ
<listcomp>‡   s    z'ROUGEScore.__init__.<locals>.<listcomp>©ÚfmeasureÚ	precisionÚrecallÚ_)Údist_reduce_fxr(   )ÚsuperÚ__init__r   ÚModuleNotFoundErrorr   Ú
isinstanceÚtupler   Ú
ValueErrorr
   r%   Úrouge_keys_valuesÚstemÚporterÚPorterStemmerÚstemmerr!   r"   r#   Ú	add_state)Úselfr    r!   r"   r#   r%   r&   r   r*   Ú	rouge_keyÚscore©Ú	__class__r(   r+   r4   j   s8   	ÿ
ÿÿ
ÿÿzROUGEScore.__init__ÚpredsÚtargetc           	   	   C   sÒ   t |tƒrtdd„ |D ƒƒrt |tƒr|gndd„ |D ƒ}t |tƒr%|g}t |tƒr.|gg}t||| j| j| j| j| j	d�}| 
¡ D ]$\}}|D ]}| 
¡ D ]\}}t| d|› d|› �ƒ | | j¡¡ qNqHqBdS )	z*Update state with predictions and targets.c                 s   s   � | ]}t |tƒV  qd S )N)r6   Ústr©r)   Útgtr(   r(   r+   Ú	<genexpr>–   s   € z$ROUGEScore.update.<locals>.<genexpr>c                 S   s   g | ]}|g‘qS r(   r(   rG   r(   r(   r+   r,   —   s    z%ROUGEScore.update.<locals>.<listcomp>)r=   r!   r"   r#   Úrouger1   N)r6   ÚlistÚallrF   r   r9   r=   r!   r"   r#   ÚitemsÚgetattrÚappendÚtoÚdevice)	r?   rD   rE   Úoutputr@   ÚmetricsÚmetricÚtpÚvaluer(   r(   r+   Úupdate’   s,   

ù	&ÿÿÿzROUGEScore.updatec                 C   sH   i }| j D ]}dD ]}t| d|› d|› �ƒ|d|› d|› �< q	qt|ƒS )zCCalculate (Aggregate and provide confidence intervals) ROUGE score.r-   rJ   r1   )r9   rN   r   )r?   Zupdate_outputr@   rU   r(   r(   r+   Úcompute­   s   
(ÿzROUGEScore.computec                 C   sH   | j jg}| jD ]}t| |ƒ}t|tƒrt|ƒ}| |¡ qtt|ƒƒS )z>Return a unique hash for the specific instance of this metric.)	rC   Ú__name__Ú	_defaultsrN   r6   rK   r7   rO   Úhash)r?   Ú	hash_valsr*   rV   r(   r(   r+   Ú__hash__¶   s   



zROUGEScore.__hash__ÚvalÚaxc                 C   s   |   ||¡S )aF  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.rouge import ROUGEScore
            >>> metric = ROUGEScore()
            >>> preds = "My name is John"
            >>> target = "Is your name John"
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torchmetrics.text.rouge import ROUGEScore
            >>> metric = ROUGEScore()
            >>> preds = "My name is John"
            >>> target = "Is your name John"
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r?   r^   r_   r(   r(   r+   ÚplotÃ   s   *r   )FNNr   r   )NN)rY   Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   Úfloatr   r   r   rF   r   r   r   r7   r   r4   rW   Údictr   rX   Úintr]   r   r   ra   Ú__classcell__r(   r(   rB   r+   r   %   sX   
 >úþýüûúùø(ÿÿ
þ	ÿÿÿþr   N)Úcollections.abcr   Útypingr   r   r   r   Útorchr   Útyping_extensionsr   Útorchmetricsr	   Ú"torchmetrics.functional.text.rouger
   r   r   r   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__Ú__doctest_requires__r   r(   r(   r(   r+   Ú<module>   s   
