Ë
    ýÿæiÄ$  ã                   ó®   — 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y)é    )Ú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                   óp  ‡ — 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Úuse_stemmerÚ
normalizerÚ	tokenizerÚ
accumulate)ÚavgÚbestÚ
rouge_keys.ÚkwargsÚreturnc                 ó8  •— t        ‰| �  d
i |¤Ž |sd|v rt        st        d«      ‚dd l}t        |t        «      s|f}|D ]  }|t        vsŒt        d|› dt        › �«      ‚ |t        vrt        d|› dt        › �«      ‚|| _
        |D �cg c]  }t        |   ‘Œ c}| _        |r$j                  j                  j                  «       nd | _        || _        || _        || _        | j                  D ]"  }	dD ]  }
| j'                  |	› d|
› �g d ¬	«       Œ Œ$ y c c}w )NÚ	rougeLsumzUStemmer 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 ©ÚfmeasureÚ	precisionÚrecallÚ_)Údist_reduce_fx© )Ú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   ÚkeyÚ	rouge_keyÚscoreÚ	__class__s              €úl/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/text/rouge.pyr.   zROUGEScore.__init__j   s8  ø€ ô 	‰ÑÑ"˜6Ò"Ù˜+¨Ñ3Ý"Ü)Økóð ó ä˜*¤eÔ,Ø$˜ˆJÛˆCØÔ,Ò,Ü Ð#9¸#¸Ð>VÔWiÐVjÐ!kÓlÐlð ð Ô6Ñ6ÜØ/°
¨|Ð;SÔTmÐSnÐoóð ð %ˆŒÙEOÓ!PÁZ¸cÔ"4°SÓ"9ÀZÑ!PˆÔÙ;F�t—y‘y×'Ñ'×5Ñ5Ô7ÈDˆŒØ$ˆŒØ"ˆŒØ$ˆŒð ŸœˆIÛ<�Ø—‘ ) ¨A¨e¨WÐ5°rÈ$�ÕOñ =ñ )ùò "Qs   ÂDÚpredsÚtargetc           
      óR  — t        |t        «      r6t        d„ |D «       «      r$t        |t        «      r|gn|D �cg c]  }|g‘Œ c}}t        |t        «      r|g}t        |t        «      r|gg}t	        ||| j
                  | j                  | j                  | j                  | j                  ¬«      }|j                  «       D ]^  \  }}|D ]T  }|j                  «       D ]?  \  }}	t        | d|› d|› �«      j                  |	j                  | j                  «      «       ŒA ŒV Œ` yc c}w )z*Update state with predictions and targets.c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w)N)r0   Ústr)Ú.0Útgts     r>   Ú	<genexpr>z$ROUGEScore.update.<locals>.<genexpr>–   s   è ø€ Ð+SÉFÀS¬J°s¼C×,@ÉFùs   ‚)r7   r   r   r   Úrouger*   N)r0   ÚlistÚallrC   r   r3   r7   r   r   r   ÚitemsÚgetattrÚappendÚtoÚdevice)
r9   r?   r@   rE   Úoutputr;   ÚmetricsÚmetricÚtpÚvalues
             r>   ÚupdatezROUGEScore.update’   s  € ô �fœdÔ#¬Ñ+SÉFÓ+SÔ(SÜ!+¨E´3Ô!7�f‘XÉvÓ=VÉvÈ¸sºeÈvÑ=VˆFä�eœSÔ!Ø�GˆEä�fœcÔ"Ø�h�ZˆFäATØØØ×"Ñ"Ø—L‘LØ—‘Ø—n‘nØ—‘ôB
ˆð #)§,¡,¦.ÑˆI�wÛ!�Ø!'§¡¦‘I�B˜Ü˜D E¨)¨°A°b°TÐ":Ó;×BÑBÀ5Ç8Á8ÈDÏKÉKÓCXÕYñ "0ñ "ñ #1ùò# >Ws   º
D$c           	      ó‚   — i }| j                   D ]$  }dD ]  }t        | d|› d|› �«      |d|› d|› �<   Œ Œ& t        |«      S )zCCalculate (Aggregate and provide confidence intervals) ROUGE score.r&   rG   r*   )r3   rK   r   )r9   Úupdate_outputr;   rR   s       r>   ÚcomputezROUGEScore.compute­   s]   € àˆØ×/Ô/ˆIÛ9�Ü:AÀ$È%ÐPYÈ{ÐZ[Ð\^Ð[_ÐH`Ó:a�  i [°°"°Ð6Ò7ñ :ð 0ô $ MÓ2Ð2ó    c                 óê   — | j                   j                  g}| j                  D ]:  }t        | |«      }t	        |t
        «      rt        |«      }|j                  |«       Œ< t        t        |«      «      S )z>Return a unique hash for the specific instance of this metric.)	r=   Ú__name__Ú	_defaultsrK   r0   rH   r1   rL   Úhash)r9   Ú	hash_valsr:   rS   s       r>   Ú__hash__zROUGEScore.__hash__¶   sc   € ð —^‘^×,Ñ,Ð-ˆ	Ø—>”>ˆCÜ˜D #Ó&ˆEÜ˜%¤Ô&Ü˜e›�Ø×Ñ˜UÕ#ð	 "ô ”E˜)Ó$Ó%Ð%rX   ÚvalÚaxc                 ó&   — | j                  ||«      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)r9   r_   r`   s      r>   ÚplotzROUGEScore.plotÃ   s   € ðT �z‰z˜#˜rÓ"Ð"rX   )FNNr    )Úrouge1Úrouge2ÚrougeLr%   )NN)rZ   Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   Úfloatr   r   r   rC   r   r	   r   r1   r   r.   rT   Údictr   rW   Úintr^   r   r   rc   Ú__classcell__)r=   s   @r>   r   r   %   sŒ  ø… ñ<ð| $Ð�tÓ#Ø!Ð�dÓ!Ø"Ð�tÓ"Ø!Ð�eÓ!Ø!Ð�eÓ!ð "Ø59Ø>BØ-3Ø2]ñ&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ZØ˜3 ¨¡Ð-Ñ.ðZØ8=¸cÀ8ÈCÁ=ÐRZÐ[cÐdgÑ[hÑRiÐ>iÑ8jðZà	óZð63˜˜c 6˜kÑ*ó 3ð&˜#ó &ð _cñ*#Ø˜E &¨(°6Ñ*:Ð":Ñ;Ñ<ð*#ØIQÐRZÑI[ð*#à	÷*#rX   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,   rX   r>   Ú<module>rz      sU   ðõ %ß 1Ó 1å Ý %å ÷ó ÷ Rß @áØ)Ð*Ðð (¨&¨Ð2Ð ôH#�õ H#rX   