Ë
    ýÿæi,A  ã                   ód  — U d dl mZ d dlmZmZmZmZmZmZm	Z	 d dl
Z
d dl
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 d d	lmZ d d
lmZmZ d dlmZ d dlmZmZ d dl m!Z!m"Z" esdgZ#dZ$e%e&d<   ererd dl'm(Z(m)Z) dd„Z* ee*«      s	ddgZ#nddgZ#dee   dee   de+e%ef   fd„Z, G d„ de«      Z-y)é    )ÚSequence)ÚAnyÚCallableÚListÚOptionalÚTupleÚUnionÚcastN)ÚTensor)ÚModule)Ú _postprocess_multiple_referencesÚ_preprocess_multiple_referencesÚ
bert_score)Ú_preprocess_text)ÚMetric)Úrank_zero_warn)Ú_SKIP_SLOW_DOCTESTÚ_try_proceed_with_timeout)Údim_zero_cat)Ú_MATPLOTLIB_AVAILABLEÚ_TRANSFORMERS_GREATER_EQUAL_4_4)Ú_AX_TYPEÚ_PLOT_OUT_TYPEzBERTScore.plotzroberta-largeÚ_DEFAULT_MODEL)Ú	AutoModelÚAutoTokenizerÚreturnc                  óp   — t        j                  t        d¬«       t        j                  t        d¬«       y)zDownload intensive operations.T)Úresume_downloadN)r   Úfrom_pretrainedr   r   © ó    úk/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/text/bert.pyÚ_download_model_for_bert_scorer$   +   s"   € ä×%Ñ%¤nÀdÕKÜ×!Ñ!¤.À$ÖGr"   Ú	BERTScoreÚ	input_idsÚattention_maskc                 óX   — t        j                  | «      t        j                  |«      dœS )z]Create an input dictionary of ``input_ids`` and ``attention_mask`` for BERTScore calculation.©r&   r'   )ÚtorchÚcatr)   s     r#   Ú_get_input_dictr,   6   s   € äŸ™ 9Ó-ÄÇÁÈ>ÓAZÑ[Ð[r"   c            )       ó&  ‡ — 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
<   ee   ed<   ee   ed<   ee   ed<   ee   ed<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dee   dee   dedee   dee   deeeeeef   gef      dededeeeej.                  f      dededededededee   d ee   d!e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eee
   ef   f   fd(„Z	 d-d)eeeee   f      d*ee   d#efd+„Zˆ xZS ).r%   a‚  `Bert_score Evaluating Text Generation`_ for measuring text similarity.

    BERT leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference
    sentences by cosine similarity. It has been shown to correlate with human judgment on sentence-level and
    system-level evaluation. Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for
    evaluating different language generation tasks. This implementation follows the original implementation from
    `BERT_score`_.

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

    - ``preds``: Predicted sentence(s). Can be one of:

        * A single predicted sentence as a string (``str``)
        * A sequence of predicted sentences (``Sequence[str]``)

    - ``target``: Target/reference sentence(s). Can be one of:

        * A single reference sentence as a string (``str``)
        * A sequence of reference sentences (``Sequence[str]``)
        * A sequence of sequences of reference sentences for multi-reference evaluation (``Sequence[Sequence[str]]``)

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

    - ``score`` (:class:`~Dict`): A dictionary containing the keys ``precision``, ``recall`` and ``f1`` with
      corresponding values

    Args:
        preds (Union[str, Sequence[str]]): A single predicted sentence or a sequence of predicted sentences.
        target (Union[str, Sequence[str], Sequence[Sequence[str]]]): A single target sentence, a sequence of target
            sentences, or a sequence of sequences of target sentences for multiple references per prediction.
        model_type: A name or a model path used to load ``transformers`` pretrained model.
        num_layers: A layer of representation to use.
        all_layers:
            An indication of whether the representation from all model's layers should be used.
            If ``all_layers=True``, the argument ``num_layers`` is ignored.
        model:  A user's own model. Must be of `torch.nn.Module` instance.
        user_tokenizer:
            A user's own tokenizer used with the own model. This must be an instance with the ``__call__`` method.
            This method must take an iterable of sentences (`List[str]`) and must return a python dictionary
            containing `"input_ids"` and `"attention_mask"` represented by :class:`~torch.Tensor`.
            It is up to the user's model of whether `"input_ids"` is a :class:`~torch.Tensor` of input ids or embedding
            vectors. This tokenizer must prepend an equivalent of ``[CLS]`` token and append an equivalent of ``[SEP]``
            token as ``transformers`` tokenizer does.
        user_forward_fn:
            A user's own forward function used in a combination with ``user_model``. This function must take
            ``user_model`` and a python dictionary of containing ``"input_ids"`` and ``"attention_mask"`` represented
            by :class:`~torch.Tensor` as an input and return the model's output represented by the single
            :class:`~torch.Tensor`.
        verbose: An indication of whether a progress bar to be displayed during the embeddings' calculation.
        idf: An indication whether normalization using inverse document frequencies should be used.
        device: A device to be used for calculation.
        max_length: A maximum length of input sequences. Sequences longer than ``max_length`` are to be trimmed.
        batch_size: A batch size used for model processing.
        num_threads: A number of threads to use for a dataloader.
        return_hash: An indication of whether the correspodning ``hash_code`` should be returned.
        lang: A language of input sentences.
        rescale_with_baseline:
            An indication of whether bertscore should be rescaled with a pre-computed baseline.
            When a pretrained model from ``transformers`` model is used, the corresponding baseline is downloaded
            from the original ``bert-score`` package from `BERT_score`_ if available.
            In other cases, please specify a path to the baseline csv/tsv file, which must follow the formatting
            of the files from `BERT_score`_.
        baseline_path: A path to the user's own local csv/tsv file with the baseline scale.
        baseline_url: A url path to the user's own  csv/tsv file with the baseline scale.
        truncation: An indication of whether the input sequences should be truncated to the ``max_length``.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from pprint import pprint
        >>> from torchmetrics.text.bert import BERTScore
        >>> preds = ["hello there", "general kenobi"]
        >>> target = ["hello there", "master kenobi"]
        >>> bertscore = BERTScore()
        >>> pprint(bertscore(preds, target))
        {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])}

    Example:
        >>> from pprint import pprint
        >>> from torchmetrics.text.bert import BERTScore
        >>> preds = ["hello there", "general kenobi"]
        >>> target = [["hello there", "master kenobi"], ["hello there", "master kenobi"]]
        >>> bertscore = BERTScore()
        >>> pprint(bertscore(preds, target))
        {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])}

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateg        Úplot_lower_boundg      ð?Úplot_upper_boundÚpreds_input_idsÚpreds_attention_maskÚtarget_input_idsÚtarget_attention_maskNÚmodel_name_or_pathÚ
num_layersÚ
all_layersÚmodelÚuser_tokenizerÚuser_forward_fnÚverboseÚidfÚdeviceÚ
max_lengthÚ
batch_sizeÚnum_threadsÚreturn_hashÚlangÚrescale_with_baselineÚbaseline_pathÚbaseline_urlÚ
truncationÚkwargsr   c                 óš  •— t        ‰| �  di |¤Ž |xs t        | _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        || _        || _        || _        || _        || _        || _        d | _        |r|| _        d| _        nTt.        st1        d«      ‚ddlm} |€t7        dt        ›d�«        |j8                  | j                  «      | _        d| _        | j;                  dg d	¬
«       | j;                  dg d	¬
«       | j;                  dg d	¬
«       | j;                  dg d	¬
«       y )NTz±`BERTScore` metric with default tokenizers requires `transformers` package be installed. Either install with `pip install transformers>=4.4` or `pip install torchmetrics[text]`.r   )r   z¤The argument `model_name_or_path` was not specified while it is required when the default `transformers` model is used. It will use the default recommended model - Ú.Fr3   r+   )Údist_reduce_fxr4   r5   r6   r!   )ÚsuperÚ__init__r   r7   r8   r9   r:   r<   r=   r>   Úembedding_devicer@   rA   rB   rC   rD   rE   rF   rG   rH   Úref_group_boundariesÚ	tokenizerr;   r   ÚModuleNotFoundErrorÚtransformersr   r   r    Ú	add_state)Úselfr7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   r   Ú	__class__s                        €r#   rN   zBERTScore.__init__ž   sa  ø€ ô, 	‰ÑÑ"˜6Ò"Ø"4Ò"F¼ˆÔØ$ˆŒØ$ˆŒØˆŒ
Ø.ˆÔØˆŒØˆŒØ &ˆÔØ$ˆŒØ$ˆŒØ&ˆÔØ&ˆÔØˆŒ	Ø%:ˆÔ"Ø*ˆÔØ(ˆÔØ$ˆŒØEIˆÔ!áØ+ˆDŒNØ"&ˆDÕå2Ü)ðpóð õ 3à!Ð)ÜðDäDRÐCUÐUVðXôð
 ;˜]×:Ñ:¸4×;RÑ;RÓSˆDŒNØ"'ˆDÔà�‰Ð(¨"¸UˆÔCØ�‰Ð-¨rÀ%ˆÔHØ�‰Ð)¨2¸eˆÔDØ�‰Ð.°À5ˆÕIr"   ÚpredsÚtargetc                 óÜ  — t        |t        «      r|g}t        |t        «      r|g}t        |t        «      st        |«      }t        |t        «      st        |«      }t        |«      t        |«      k7  r#t	        dt        |«      › dt        |«      › �«      ‚t        |t        «      rAt        |«      dkD  r3t        |t        «      r#t        |«      dkD  rt        ||«      \  }}| _        t        || j                  | j                  | j                  d| j                  ¬«      \  }}t        t        t        t           |«      | j                  | j                  | j                  d| j                  ¬«      \  }}| j                  j                  |d   «       | j                   j                  |d   «       | j"                  j                  |d   «       | j$                  j                  |d   «       y)	z¡Store predictions/references for computing BERT scores.

        It is necessary to store sentences in a tokenized form to ensure the DDP mode working.

        zLExpected number of predicted and reference sentences to be the same, but gotz and r   F)rH   Úsort_according_lengthÚown_tokenizerr&   r'   N)Ú
isinstanceÚstrÚlistÚlenÚ
ValueErrorr   rP   r   rQ   r@   rH   r;   r
   r   r3   Úappendr4   r5   r6   )rU   rW   rX   Ú
preds_dictÚ_Útarget_dicts         r#   ÚupdatezBERTScore.updateá   s£  € ô �eœSÔ!Ø�GˆEÜ�fœcÔ"Ø�XˆFÜ˜%¤Ô&Ü˜“KˆEÜ˜&¤$Ô'Ü˜&“\ˆFäˆu‹:œ˜V›Ò$ÜØ^Ü�u“:�,˜e¤C¨£K =ð2óð ô
 �eœTÔ"¤s¨5£z°A¢~¼*ÀVÌTÔ:RÔWZÐ[aÓWbÐefÒWfÜ7VÐW\Ð^dÓ7eÑ4ˆE�6˜4Ô4ä(ØØ�N‰NØ�O‰OØ—‘Ø"'Ø×-Ñ-ô
‰ˆ
�Aô *Ü””c‘˜FÓ#Ø�N‰NØ�O‰OØ—‘Ø"'Ø×-Ñ-ô
‰ˆ�Qð 	×Ñ×#Ñ# J¨{Ñ$;Ô<Ø×!Ñ!×(Ñ(¨Ð4DÑ)EÔFØ×Ñ×$Ñ$ [°Ñ%=Ô>Ø×"Ñ"×)Ñ)¨+Ð6FÑ*GÕHr"   c                 óŒ  — t        | j                  «      t        | j                  «      dœ}t        | j                  «      t        | j                  «      dœ}t        di d|“d|“d| j                  “d| j                  “d| j                  “d| j                  “d| j                  r| j                  nd	“d
| j                  “d| j                  “d| j                  “d| j                  “d| j                   “d| j"                  “d| j$                  “d| j&                  “d| j(                  “d| j*                  “d| j,                  “d| j.                  “Ž}| j0                  �gt3        |d   t4        «      rTt3        |d   t4        «      rAt3        |d   t4        «      r.t7        |d   |d   |d   | j0                  «      \  |d<   |d<   |d<   |S )zCalculate BERT scores.r)   rW   rX   r7   r8   r9   r:   r;   Nr<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   Ú	precisionÚrecallÚf1r!   )r   r3   r4   r5   r6   r   r7   r8   r9   r:   r;   rQ   r<   r=   r>   rO   r@   rA   rB   rC   rD   rE   rF   rG   rP   r\   r   r   )rU   rW   rX   Úoutput_dicts       r#   ÚcomputezBERTScore.compute  sô  € ô & d×&:Ñ&:Ó;Ü*¨4×+DÑ+DÓEñ
ˆô
 & d×&;Ñ&;Ó<Ü*¨4×+EÑ+EÓFñ
ˆô
 !ò 
Ùð
áð
ð  $×6Ò6ð
ð —’ð	
ð
 —’ð
ð —*’*ð
ð .2×-@Ò-@˜4Ÿ>š>Àdøð
ð !×0Ò0ð
ð —L’Lð
ð —’ð
ð ×(Ò(ð
ð —’ð
ð —’ð
ð ×(Ò(ð
ð ×(Ò(ð
ð  —’ð!
ð" #'×"<Ò"<ð#
ð$ ×,Ò,ð%
ð& ×*Ò*ð'
ˆð. ×%Ñ%Ð1Ü˜; {Ñ3´VÔ<Ü˜; xÑ0´&Ô9Ü˜; tÑ,¬fÔ5äQqØ˜KÑ(¨+°hÑ*?ÀÈTÑARÐTX×TmÑTmóRÑNˆK˜Ñ$ k°(Ñ&;¸[ÈÑ=Nð Ðr"   ÚvalÚaxc                 óÞ   — |€T| j                  «       }|j                  «       D ��ci c])  \  }}|t        j                  |«      j	                  «       “Œ+ }}}| j                  ||«      S c c}}w )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.bert import BERTScore
            >>> preds = ["hello there", "general kenobi"]
            >>> target = ["hello there", "master kenobi"]
            >>> metric = BERTScore()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import tensor
            >>> from torchmetrics.text.bert import BERTScore
            >>> preds = ["hello there", "general kenobi"]
            >>> target = ["hello there", "master kenobi"]
            >>> metric = BERTScore()
            >>> values = []
            >>> for _ in range(10):
            ...     val = metric(preds, target)
            ...     val = {k: tensor(v).mean() for k,v in val.items()}  # convert into single value per key
            ...     values.append(val)
            >>> fig_, ax_ = metric.plot(values)

        )rk   Úitemsr*   ÚtensorÚmeanÚ_plot)rU   rl   rm   ÚkÚvs        r#   ÚplotzBERTScore.plot>  s`   € ðZ ˆ;Ø—,‘,“.ˆCØ9<¿¹¼ÔE¹±°°A�1”e—l‘l 1“o×*Ñ*Ó,Ñ,¸ˆCÑEØ�z‰z˜#˜rÓ"Ð"ùó Fs   ¦.A))NNFNNNFFNi   é@   r   FÚenFNNF)NN) Ú__name__Ú
__module__Ú__qualname__Ú__doc__r.   ÚboolÚ__annotations__r/   r0   r1   Úfloatr2   r   r   r   r]   Úintr   r   r   Údictr	   r*   r?   rN   r   re   rk   r   r   ru   Ú__classcell__)rV   s   @r#   r%   r%   ;   s”  ø… ñUðn $Ð�tÓ#Ø!Ð�dÓ!Ø#Ð�tÓ#Ø!Ð�eÓ!Ø!Ð�eÓ!à˜&‘\Ó!Ø˜v™,Ó&Ø˜6‘lÓ"Ø ™<Ó'ð -1Ø$(Ø Ø"&Ø(,ØSWØØØ59ØØØØ!ØØ&+Ø'+Ø&*Ø ñ'AJà$ S™MðAJð ˜S‘MðAJð ð	AJð
 ˜ÑðAJð ! ™ðAJð " (¨F°D¸¸f¸Ñ4EÐ+FÈÐ+NÑ"OÑPðAJð ðAJð ðAJð ˜˜s E§L¡LÐ0Ñ1Ñ2ðAJð ðAJð ðAJð ðAJð ðAJð ðAJð   $ð!AJð"   ‘}ð#AJð$ ˜s‘mð%AJð& ð'AJð( ð)AJð* 
õ+AJðF.IØ˜3 ¨¡Ð-Ñ.ð.IØ8=¸cÀ8ÈCÁ=ÐRZÐ[cÐdgÑ[hÑRiÐ>iÑ8jð.Ià	ó.Ið`+˜˜c 5¨°°e±¸cÐ)AÑ#BÐBÑCó +ð\ _cñ0#Ø˜E &¨(°6Ñ*:Ð":Ñ;Ñ<ð0#ØIQÐRZÑI[ð0#à	÷0#r"   )r   N).Úcollections.abcr   Útypingr   r   r   r   r   r	   r
   r*   r   Útorch.nnr   Ú!torchmetrics.functional.text.bertr   r   r   Ú4torchmetrics.functional.text.helper_embedding_metricr   Útorchmetrics.metricr   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.checksr   r   Útorchmetrics.utilities.datar   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r]   r}   rS   r   r   r$   r€   r,   r%   r!   r"   r#   Ú<module>rŽ      sÈ   ðö %ß D× DÑ Dã Ý Ý ÷ñ õ
 RÝ &Ý 1ß WÝ 4ß aß @áØ(Ð)Ðð &€�Ó %áÑ9ß5óHñ
 %Ð%CÔDØ'Ð)9Ð:Ñà#Ð%5Ð6Ðð\˜t F™|ð \¸TÀ&¹\ð \ÈdÐSVÐX^ÐS^ÑN_ó \ô
s#�õ s#r"   