a
    d$                     @   s   d dl mZmZmZmZ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sdgZd	d
giZG dd deZdS )    )AnyCallableDictListOptionalSequenceTuple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                
       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eeeegef  eeegee f  ed eeeedf f edd fddZeeee f eeee eee  f ddddZeeef dddZedddZdeeeee f  ee ed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``, spliting 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Zrouge1Zrouge2ZrougeL	rougeLsum)avgr   .)use_stemmer
normalizer	tokenizer
accumulate
rouge_keyskwargsreturnc                    s   t  jf i | |sd|v r2ts*tddd l}t|tsB|f}|D ] }|tvrFtd| dt qF|t	vrtd| dt	 || _
dd |D | _|r|jj nd | _|| _|| _|| _| j
D ](}	d	D ]}
| j|	 d
|
 g d d qqd 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(   `/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/text/rouge.py
<listcomp>       z'ROUGEScore.__init__.<locals>.<listcomp>ZfmeasureZ	precisionZrecall_)Zdist_reduce_fx)super__init__r   ModuleNotFoundErrorr   
isinstancetupler   
ValueErrorr   r%   rouge_keys_valuesstemZporterZPorterStemmerstemmerr"   r#   r$   Z	add_state)selfr!   r"   r#   r$   r%   r&   r   r*   	rouge_keyZscore	__class__r(   r+   r1   i   s2    	

zROUGEScore.__init__)predstargetr'   c           	   	   C   s   t |tr:tdd |D r:t |tr,|gndd |D }t |trJ|g}t |tr\|gg}t||| j| j| j| j| j	d}|
 D ]H\}}|D ]:}|
 D ],\}}t| d| d| || j qqqdS )	z*Update state with predictions and targets.c                 s   s   | ]}t |tV  qd S )N)r3   strr)   Ztgtr(   r(   r+   	<genexpr>   r-   z$ROUGEScore.update.<locals>.<genexpr>c                 S   s   g | ]
}|gqS r(   r(   r@   r(   r(   r+   r,      r-   z%ROUGEScore.update.<locals>.<listcomp>)r8   r"   r#   r$   rouger/   N)r3   listallr?   r   r6   r8   r"   r#   r$   itemsgetattrappendtoZdevice)	r9   r=   r>   outputr:   ZmetricsZmetrictpvaluer(   r(   r+   update   s&    

	zROUGEScore.update)r'   c                 C   sH   i }| j D ]4}dD ]*}t| d| d| |d| d| < qq
t|S )zCCalculate (Aggregate and provide confidence intervals) ROUGE score.r.   rB   r/   )r6   rF   r   )r9   Zupdate_outputr:   rJ   r(   r(   r+   compute   s
    
*zROUGEScore.computec                 C   sH   | j jg}| jD ]*}t| |}t|tr0t|}|| qtt|S )z>Return a unique hash for the specific instance of this metric.)	r<   __name__	_defaultsrF   r3   rC   r4   rG   hash)r9   Z	hash_valsr*   rK   r(   r(   r+   __hash__   s    



zROUGEScore.__hash__)valaxr'   c                 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)

        )Z_plot)r9   rR   rS   r(   r(   r+   plot   s    *r   )FNNr   r   )NN)rN   
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   r   r?   r   r   r	   r   r   r1   rL   r   r
   rM   intrQ   r   r   rT   __classcell__r(   r(   r;   r+   r   $   s<   
>     )&	 r   N)typingr   r   r   r   r   r   r   r	   Ztorchr
   Ztyping_extensionsr   Ztorchmetricsr   Z"torchmetrics.functional.text.rouger   r   r   r   Ztorchmetrics.utilities.importsr   r   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__Z__doctest_requires__r   r(   r(   r(   r+   <module>   s   (
