§
    ’©ºjÄ$  ã                   ó¶   — 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sd	gZd
dgiZ G 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_TYPEzROUGEScore.plot)Ú
ROUGEScoreÚnltkc                   óâ  ‡ — 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„Zdeeee         f         deeee         eee                  f         ddfd„Zdeeef         fd„Zdefd„Z	 d!deeeee         f                  dee         defd„Zˆ x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                 ó@  •—  t          ¦   «         j        di |¤Ž |sd|v rt          st          d¦  «        ‚dd l}t          |t          ¦  «        s|f}|D ]%}|t          vrt          d|› dt          › �¦  «        ‚Œ&|t          vrt          d|› dt          › �¦  «        ‚|| _
        d„ |D ¦   «         | _        |r|j        j                             ¦   «         nd | _        || _        || _        || _        | j
        D ]$}	dD ]}
|                      |	› d	|
› �g d ¬
¦  «         Œ Œ%d 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                 ó(   — g | ]}t           |         ‘ŒS © )r   )Ú.0Úkeys     úg/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/text/rouge.pyú
<listcomp>z'ROUGEScore.__init__.<locals>.<listcomp>‡   s   € Ð!PÐ!PÐ!P¸cÕ"4°SÔ"9Ð!PÐ!PÐ!Pó    ©Ú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__s              €r.   r8   zROUGEScore.__init__j   s¢  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Øð 	˜+¨Ð3Ð3Ý"ð Ý)Økñô ð ð ˆKˆKˆKå˜*¥eÑ,Ô,ð 	'Ø$˜ˆJØð 	mð 	mˆCØÕ,Ð,Ð,Ý Ð!k¸#Ð!kÐ!kÕWiÐ!kÐ!kÑlÔlÐlð -ð Õ6Ð6Ð6ÝØo°
ÐoÐoÕTmÐoÐoñô ð ð %ˆŒØ!PÐ!PÀZÐ!PÑ!PÔ!PˆÔØ;FÐP�t”yÔ'×5Ò5Ñ7Ô7Ð7ÈDˆŒØ$ˆŒØ"ˆŒØ$ˆŒð œð 	Pð 	PˆIØ<ð Pð P�Ø—’ )Ð5Ð5¨eÐ5Ð5°rÈ$�ÑOÔOÐOÐOðPð	Pð 	Pr0   ÚpredsÚtargetc           
      ó^  — t          |t          ¦  «        r=t          d„ |D ¦   «         ¦  «        r$t          |t          ¦  «        r|gnd„ |D ¦   «         }t          |t          ¦  «        r|g}t          |t          ¦  «        r|gg}t	          ||| j        | j        | j        | j        | j	        ¬¦  «        }| 
                    ¦   «         D ]e\  }}|D ]]}| 
                    ¦   «         D ]F\  }}t          | d|› d|› �¦  «                             |                     | j        ¦  «        ¦  «         ŒGŒ^ŒfdS )z*Update state with predictions and targets.c              3   ó@   K  — | ]}t          |t          ¦  «        V — Œd S )N)r:   Ústr©r,   Útgts     r.   ú	<genexpr>z$ROUGEScore.update.<locals>.<genexpr>–   s,   è è € Ð+SÐ+SÀS­J°s½CÑ,@Ô,@Ð+SÐ+SÐ+SÐ+SÐ+SÐ+Sr0   c                 ó   — g | ]}|g‘ŒS r+   r+   rL   s     r.   r/   z%ROUGEScore.update.<locals>.<listcomp>—   s   € Ð=VÐ=VÐ=VÈ¸s¸eÐ=VÐ=VÐ=Vr0   )rA   r"   r#   r$   Úrouger5   N)r:   ÚlistÚallrK   r   r=   rA   r"   r#   r$   ÚitemsÚgetattrÚappendÚtoÚdevice)	rC   rG   rH   ÚoutputrD   ÚmetricsÚmetricÚtpÚvalues	            r.   ÚupdatezROUGEScore.update’   sp  € õ �f�dÑ#Ô#ð 	W­Ð+SÐ+SÈFÐ+SÑ+SÔ+SÑ(SÔ(Sð 	WÝ!+¨Eµ3Ñ!7Ô!7ÐV�f�X�XÐ=VÐ=VÈvÐ=VÑ=VÔ=VˆFå�e�SÑ!Ô!ð 	Ø�GˆEå�f�cÑ"Ô"ð 	 Ø�h�ZˆFåATØØØÔ"Ø”LØ”Ø”nØ”ðB
ñ B
ô B
ˆð #)§,¢,¡.¤.ð 	Zð 	ZÑˆI�wØ!ð Zð Z�Ø!'§¢¡¤ð Zð Z‘I�B˜Ý˜DÐ":¨)Ð":Ð":°bÐ":Ð":Ñ;Ô;×BÒBÀ5Ç8Â8ÈDÌKÑCXÔCXÑYÔYÐYÐYðZðZð	Zð 	Zr0   c           	      ó€   — i }| j         D ]&}dD ]!}t          | d|› d|› �¦  «        |d|› d|› �<   Œ"Œ't          |¦  «        S )zCCalculate (Aggregate and provide confidence intervals) ROUGE score.r1   rP   r5   )r=   rT   r   )rC   Úupdate_outputrD   r[   s       r.   ÚcomputezROUGEScore.compute­   s}   € àˆØÔ/ð 	bð 	bˆIØ9ð bð b�Ý:AÀ$ÐH`ÐPYÐH`ÐH`Ð\^ÐH`ÐH`Ñ:aÔ:a�Ð6 iÐ6Ð6°"Ð6Ð6Ñ7Ð7ðbõ $ MÑ2Ô2Ð2r0   c                 óú   — | j         j        g}| j        D ]K}t          | |¦  «        }t	          |t
          ¦  «        rt          |¦  «        }|                     |¦  «         ŒLt          t          |¦  «        ¦  «        S )z>Return a unique hash for the specific instance of this metric.)	rF   Ú__name__Ú	_defaultsrT   r:   rQ   r;   rU   Úhash)rC   Ú	hash_valsr-   r\   s       r.   Ú__hash__zROUGEScore.__hash__¶   s{   € ð ”^Ô,Ð-ˆ	Ø”>ð 	$ð 	$ˆCÝ˜D #Ñ&Ô&ˆEÝ˜%¥Ñ&Ô&ð %Ý˜e™œ�Ø×Ò˜UÑ#Ô#Ð#Ð#å•E˜)Ñ$Ô$Ñ%Ô%Ð%r0   ÚvalÚaxc                 ó.   — |                       ||¦  «        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)rC   rg   rh   s      r.   ÚplotzROUGEScore.plotÃ   s   € ðT �zŠz˜#˜rÑ"Ô"Ð"r0   )FNNr   r   )NN)rb   Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   Úfloatr   r   r   rK   r   r	   r   r;   r   r8   r]   Údictr   r`   Úintrf   r   r   rk   Ú__classcell__)rF   s   @r.   r   r   %   s5  ø€ € € € € € ð<ð <ð| $Ð�tÐ#Ð#Ñ#Ø!Ð�dÐ!Ð!Ñ!Ø"Ð�tÐ"Ð"Ñ"Ø!Ð�eÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!ð "Ø59Ø>BØ-3Ø2]ð&Pð &Pàð&Pð ˜X s e¨S jÔ1Ô2ð&Pð ˜H c U¨H°S¬MÐ%9Ô:Ô;ð	&Pð
 ˜MÔ*ð&Pð ˜#˜u S¨# XœÐ.Ô/ð&Pð ð&Pð 
ð&Pð &Pð &Pð &Pð &Pð &PðPZØ˜3 ¨¤Ð-Ô.ðZØ8=¸cÀ8ÈCÄ=ÐRZÐ[cÐdgÔ[hÔRiÐ>iÔ8jðZà	ðZð Zð Zð Zð63˜˜c 6˜kÔ*ð 3ð 3ð 3ð 3ð&˜#ð &ð &ð &ð &ð _cð*#ð *#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð*#ØIQÐRZÔI[ð*#à	ð*#ð *#ð *#ð *#ð *#ð *#ð *#ð *#r0   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+   r0   r.   ú<module>r      s@  ðð %Ð $Ð $Ð $Ð $Ð $Ø 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1Ð 1à Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %à Ð Ð Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð RÐ QÐ QÐ QÐ QÐ QÐ QÐ QØ @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð +Ø)Ð*Ðð (¨&¨Ð2Ð ðH#ð H#ð H#ð H#ð H#�ñ H#ô H#ð H#ð H#ð H#r0   