Ë
    þÍ:jzh  ã            0       ó   — d dl Z d dlZd dlZd dlmZmZ 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 d dlmZmZmZmZmZmZmZ d d	lmZ d d
l m!Z!m"Z" d dl#m$Z$m%Z% eded   fd„«       Z&dZ'e%rd dl(m)Z)m*Z* d?d„Z+e!r e"e+«      sdgZ,ndgZ,	 	 	 	 	 	 d@dede-dedeee.ej^                  f      dee-   de0de0de0dee
ee1e.ef   gef      deeef   fd„Z2dede.dedefd„Z3d ed!ed"ed#edeeeef   f
d$„Z4dAd%ee.   dee-   de0de.fd&„Z5d'e.defd(„Z6d)e.defd*„Z7	 	 	 	 dBd+e.d%ee.   d'ee.   d)ee.   dee   f
d,„Z8	 	 dCd-ed.ed/ed0edee-   de0deeeef   fd1„Z9d2ee.   d3eee.ee.   f      deee.   ee.   eeee-e-f         f   fd4„Z:d-ed.ed/ed5eee-e-f      deeeef   f
d6„Z;	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDd2ee.ee.   e1e.ef   f   d3ee.ee.   eee.      e1e.ef   f   d%ee.   dee-   de0dee   d7e	dee
ee1e.ef   gef      de0de0deee.ej^                  f      d8e-d9e-d:e-d;e0d+e.d<e0d'ee.   d)ee.   d=e0de1e.eeee<   e.f   f   f*d>„Z=y)Eé    N)ÚIteratorÚSequence)Úcontextmanager)ÚAnyÚCallableÚListÚOptionalÚTupleÚUnionÚcast)ÚTensor)ÚModule)Ú
DataLoader)ÚTextDatasetÚTokenizedDatasetÚ_check_shape_of_model_outputÚ_get_progress_barÚ_input_data_collatorÚ_output_data_collatorÚ*_process_attention_mask_for_special_tokens)Úrank_zero_warn)Ú_SKIP_SLOW_DOCTESTÚ_try_proceed_with_timeout)Ú_TQDM_AVAILABLEÚ_TRANSFORMERS_GREATER_EQUAL_4_4Úreturnc               #   óì   K  — t        j                  d«      } | j                  «       }	 | j                  t         j                  «       d–— | j                  |«       y# | j                  |«       w xY w­w)z]Ignore irrelevant fine-tuning warning from transformers when loading the model for BertScore.ztransformers.modeling_utilsN)ÚloggingÚ	getLoggerÚgetEffectiveLevelÚsetLevelÚERROR)ÚloggerÚoriginal_levels     úv/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/torchmetrics/functional/text/bert.pyÚ_ignore_log_warningr&   (   sW   è ø€ ô ×ÑÐ<Ó=€FØ×-Ñ-Ó/€Nð(Ø�‰œŸ™Ô&Ûà�‰˜Õ'øˆ�‰˜Õ'üs   ‚&A4©#A ÁA4ÁA1Á1A4zroberta-large)Ú	AutoModelÚAutoTokenizerc                  ó¦   — t        «       5  t        j                  t        «       t	        j                  t        «       ddd«       y# 1 sw Y   yxY w)zDownload intensive operations.N)r&   r(   Úfrom_pretrainedÚ_DEFAULT_MODELr'   © ó    r%   Ú_download_model_for_bert_scorer.   :   s9   € ä Ó"ñ 	6Ü×)Ñ)¬.Ô9Ü×%Ñ%¤nÔ5÷	6÷ 	6ñ 	6ús   ‹3AÁAÚ
bert_scoreÚ
dataloaderÚ
target_lenÚmodelÚdeviceÚ
num_layersÚ
all_layersÚidfÚverboseÚuser_forward_fnc	           
      ó  — g }	g }
t        | |«      D �]­  }t        j                  «       5  t        ||«      }|sQ|s% ||d   |d   d¬«      }|j                  |�|nd   }n |||«      }t        ||d   «       |j                  d«      }n\|rt        d«      ‚ ||d   |d   d¬«      }t        j                  |j                  D �cg c]  }|j                  d«      ‘Œ c}d¬	«      }ddd«       |j                  d¬	«      j                  d«      z  }t        ||d   |«      \  }}t        |«      }t        j                  d
||«      }|	j                  |j                  «       «       |r|d   |z  n|j                  |j                   «      }||j#                  dd¬«      z  }|
j                  |j                  «       «       �Œ° t        j                  |	«      }t        j                  |
«      }||fS c c}w # 1 sw Y   �ŒxY w)a<  Calculate sentence embeddings and the inverse-document-frequency scaling factor.

    Args:
        dataloader: dataloader instance.
        target_len: A length of the longest sequence in the data. Used for padding the model output.
        model: BERT model.
        device: A device to be used for calculation.
        num_layers: The layer of representation to use.
        all_layers: An indication whether representation from all model layers should be used for BERTScore.
        idf: An Indication whether normalization using inverse document frequencies should be used.
        verbose: An indication of whether a progress bar to be displayed during the embeddings' calculation.
        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`.

    Return:
        A tuple of :class:`~torch.Tensor`s containing the model's embeddings and the normalized tokens IDF.
        When ``idf = False``, tokens IDF is not calculated, and a matrix of mean weights is returned instead.
        For a single sentence, ``mean_weight = 1/seq_len``, where ``seq_len`` is a sum over the corresponding
        ``attention_mask``.

    Raises:
        ValueError:
            If ``all_layers = True`` and a model, which is not from the ``transformers`` package, is used.

    Ú	input_idsÚattention_maskT)Úoutput_hidden_statesNéÿÿÿÿé   zQThe option `all_layers=True` can be used only with default `transformers` models.©Údimzblsd, bs -> blsdÚinput_ids_idf)Úkeepdim)r   ÚtorchÚno_gradr   Úhidden_statesr   Ú	unsqueezeÚ
ValueErrorÚcatÚnormr   r   ÚeinsumÚappendÚcpuÚtypeÚdtypeÚsum)r0   r1   r2   r3   r4   r5   r6   r7   r8   Úembeddings_listÚidf_scale_listÚbatchÚoutÚor;   Úprocessed_attention_maskrA   Ú
embeddingsÚ	idf_scales                      r%   Ú_get_embeddings_and_idf_scalerX   F   s  € ðN %'€OØ#%€NÜ" :¨wÓ7ó  3ˆÜ�]‰]‹_ñ 	TÜ(¨°Ó7ˆEáÙ&Ù  kÑ 2°EÐ:JÑ4KÐbfÔg�CØ×+Ñ+¸*Ð:P©JÐVXÑY‘Cá)¨%°Ó7�CÜ0°°e¸KÑ6HÔIØ—m‘m AÓ&‘á"Ü$Økóð ñ ˜E +Ñ.°Ð6FÑ0GÐ^bÔc�Ü—i‘i¸×9JÑ9JÖ K°A §¡¨Q¥Ò KÐQRÔS�÷#	Tð& 	ˆs�x‰x˜BˆxÓ×)Ñ)¨"Ó-Ñ-ˆÜ3°C¸Ð?OÑ9PÐR\Ó]Ñˆˆ^Ü#MÈnÓ#]Ð ä�l‰lÐ-¨sÐ4LÓMˆØ×Ñ˜sŸw™w›yÔ)ñ BEˆE�/Ñ"Ð%=Ò=ÐJb×JgÑJgÐhk×hqÑhqÓJrð 	ð 	˜×*Ñ*¨2°tÐ*Ó<Ñ<ˆØ×Ñ˜m×/Ñ/Ó1Ö2ðA 3ôD —‘˜?Ó+€JÜ—	‘	˜.Ó)€Ià�yÐ Ð ùò' !L÷#	Tñ 	Tús   ©BG5ÃG0Ã	G5Ç0G5Ç5G?	Úcos_simÚmetricrW   c                 óØ   — |dk(  rdnd}| j                  |¬«      j                  }t        j                  d||«      j	                  d«      }|j                  dd«      j                  «       S )	zOCalculate precision or recall, transpose it and scale it with idf_scale factor.Ú	precisioné   é   r?   zbls, bs -> blsr=   r   r>   )ÚmaxÚvaluesrC   rJ   rO   Ú	transposeÚsqueeze)rY   rZ   rW   r@   Úress        r%   Ú_get_scaled_precision_or_recallrd   —   s^   € à˜Ò$‰!¨!€CØ
�+‰+˜#ˆ+Ó
×
%Ñ
%€CÜ
�,‰,Ð'¨¨iÓ
8×
<Ñ
<¸RÓ
@€Cà�=‰=˜˜AÓ×&Ñ&Ó(Ð(r-   Úpreds_embeddingsÚtarget_embeddingsÚpreds_idf_scaleÚtarget_idf_scalec                 óÔ   — t        j                  d| |«      }t        |d|«      }t        |d|«      }d|z  |z  ||z   z  }|j                  t        j                  |«      d«      }|||fS )a¿  Calculate precision, recall and F1 score over candidate and reference sentences.

    Args:
        preds_embeddings: Embeddings of candidate sentences.
        target_embeddings: Embeddings of reference sentences.
        preds_idf_scale: An IDF scale factor for candidate sentences.
        target_idf_scale: An IDF scale factor for reference sentences.

    Return:
        Tensors containing precision, recall and F1 score, respectively.

    zblpd, blrd -> blprr\   Úrecallr^   ç        )rC   rJ   rd   Úmasked_fillÚisnan)re   rf   rg   rh   rY   r\   rj   Úf1_scores           r%   Ú_get_precision_recall_f1ro       sv   € ô  �l‰lÐ/Ð1AÐCTÓU€Gä/°¸ÀoÓV€IÜ,¨W°hÐ@PÓQ€Fà�9‰}˜vÑ%¨°VÑ);Ñ<€HØ×#Ñ#¤E§K¡K°Ó$9¸3Ó?€Hà�f˜hÐ&Ð&r-   Úmodel_name_or_pathc                 ó    — | › d|› |rd› �S d› �S )z,Compute `BERT_score`_ (copied and adjusted).Ú_LÚ_idfz_no-idfr,   )rp   r4   r6   s      r%   Ú	_get_hashrt   »   s&   € à Ð!  J <¹#°Ð/MÐNÐNÀ9Ð/MÐNÐNr-   Úbaseline_pathc                 ó8  — t        | «      5 }t        j                  |«      }t        |«      D ���cg c]$  \  }}|dkD  sŒ|D �cg c]  }t	        |«      ‘Œ c}‘Œ& }}}}ddd«       t        j                  «      dd…dd…f   S c c}w c c}}}w # 1 sw Y   Œ3xY w)zqRead baseline from csv file from the local file.

    This method implemented to avoid `pandas` dependency.

    r   Nr>   )ÚopenÚcsvÚreaderÚ	enumerateÚfloatrC   Útensor)ru   ÚfnameÚcsv_fileÚidxÚrowÚitemÚbaseline_lists          r%   Ú_read_csv_from_local_filerƒ   À   s‘   € ô 
ˆmÓ	ð g Ü—:‘:˜eÓ$ˆÜGPÐQYÓGZ×fÐf¹8¸3ÀÐ^aÐdeÓ^e°#Ö6¨$œ% �+Ô6ÐfˆÒf÷gô �<‰<˜Ó&¢q¨!©" uÑ-Ð-ùò 7ùÔf÷gð gús3   Œ%B±B	
¿B	
ÁBÁB	
ÁBÂB	
Â	BÂBÚbaseline_urlc                 óŽ  — t         j                  j                  | «      5 }t        |«      D ���cg c]O  \  }}|dkD  rE|j	                  «       j                  d«      j                  d«      D �cg c]  }t        |«      ‘Œ c}‘ŒQ }}}}t        j                  |«      dd…dd…f   cddd«       S c c}w c c}}}w # 1 sw Y   yxY w)ziRead baseline from csv file from URL.

    This method is implemented to avoid `pandas` dependency.

    r   zutf-8ú,Nr>   )
ÚurllibÚrequestÚurlopenrz   ÚstripÚdecodeÚsplitr{   rC   r|   )r„   Úhttp_requestr   r€   r�   r‚   s         r%   Ú_read_csv_from_urlrŽ   Ì   s²   € ô 
�‰×	Ñ	 Ó	-ð 2°ô & lÓ3÷
ð 
á��SØ�QŠwð &)§Y¡Y£[×%7Ñ%7¸Ó%@×%FÑ%FÀsÓ%KÖL˜TŒU�4�[ÔLð
ˆò 
ô
 �|‰|˜MÓ*ª1¨a©b¨5Ñ1÷2ñ 2ùâLùô
÷2ð 2ús.    B;°=B4
Á-B/Á?B4
Â!B;Â/B4
Â4B;Â;CÚlangc                 ó’   — |rt        |«      }|S |rt        |«      }|S | r|rd}|› d| › d|› d�}t        |«      }|S t        d«       y)z<Load a CSV file with the baseline values used for rescaling.zWhttps://raw.githubusercontent.com/Tiiiger/bert_score/master/bert_score/rescale_baselineú/z.tsvzFBaseline was not successfully loaded. No baseline is going to be used.N)rƒ   rŽ   r   )r�   rp   ru   r„   ÚbaselineÚurl_bases         r%   Ú_load_baseliner”   Û   st   € ñ Ü%>¸}Ó%Mˆð €Oñ 
Ü% lÓ3ˆð €Oñ 
Ñ$ØlˆØ"˜ 1 T F¨!Ð,>Ð+?¸tÐDˆÜ% lÓ3ˆð
 €Oô 	Ð_Ô`Ør-   r\   rj   rn   r’   c                 ó¨   — |€|du rd}t        j                  | ||gd¬«      }|r|j                  d«      n||   }||z
  d|z
  z  }|d   |d   |d   fS )z<Rescale the computed metrics with the pre-computed baseline.Fr=   r?   r>   ).r   ).r>   ).r^   )rC   ÚstackrF   )r\   rj   rn   r’   r4   r5   Úall_metricsÚbaseline_scales           r%   Ú_rescale_metrics_with_baseliner™   ò   sv   € ð Ð˜j¨EÑ1Øˆ
Ü—+‘+˜y¨&°(Ð;ÀÔD€KÙ.8�X×'Ñ'¨Ô*¸hÀzÑ>R€NØ Ñ/°A¸Ñ4FÑG€Kà�vÑ ¨FÑ 3°[ÀÑ5HÐHÐHr-   ÚpredsÚtargetc                 ó€  — t        d„ | D «       «      st        d«      ‚t        d„ |D «       «      }|rôg }g }g }d}t        | |«      D ]Ø  \  }}t	        |t
        t        f«      rr|j                  |gt        |«      z  «       |j                  t        t        t           |«      «       |j                  ||t        |«      z   f«       |t        |«      z  }ŒŽ|j                  |«       |j                  t        t        |«      «       |j                  ||dz   f«       |dz  }ŒÚ |||fS | t        t        t           |«      dfS )a®  Preprocesses predictions and targets when dealing with multiple references.

    This function handles the case where a single prediction might have multiple
    reference targets (represented as a list/tuple of strings).

    Args:
        preds: A list of predictions
        target: A list of targets, where each item could be a string or a list/tuple of strings

    Returns:
        Tuple: (preds, target, ref_group_boundaries)
            - preds: Flattened list of `str`
            - target: Flattened list of `str`
            - ref_group_boundaries: List of tuples (start, end) indicating the boundaries
              of reference groups in the flattened lists or `None`

    c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w©N)Ú
isinstanceÚstr©Ú.0r�   s     r%   ú	<genexpr>z2_preprocess_multiple_references.<locals>.<genexpr>  s   è ø€ Ò7¨Œz˜$¤×$Ñ7ùs   ‚úInvalid input provided.c              3   óH   K  — | ]  }t        |t        t        f«      –— Œ y ­wrž   )rŸ   ÚlistÚtupler¡   s     r%   r£   z2_preprocess_multiple_references.<locals>.<genexpr>  s   è ø€ ÒRÀ4œz¨$´´u°×>ÑRùs   ‚ "r   r>   N)ÚallrG   ÚanyÚziprŸ   r¦   r§   ÚextendÚlenr   r   r    rK   )	rš   r›   Úhas_nested_sequencesÚref_group_boundariesÚ	new_predsÚ
new_targetÚcountÚpredÚ	ref_groups	            r%   Ú_preprocess_multiple_referencesr´     s6  € ô( Ñ7°Ô7Ô7ÜÐ2Ó3Ð3äÑRÈ6ÔRÓRÐáØ68ÐØ!ˆ	Ø "ˆ
Øˆä" 5¨&Ó1ò 
	‰OˆD�)Ü˜)¤d¬E ]Ô3Ø× Ñ  $ ¬#¨i«.Ñ!8Ô9Ø×!Ñ!¤$¤t¬C¡y°)Ó"<Ô=Ø$×+Ñ+¨U°E¼CÀ	»NÑ4JÐ,KÔLØœ˜Y›Ñ'‘à× Ñ  Ô&Ø×!Ñ!¤$¤s¨IÓ"6Ô7Ø$×+Ñ+¨U°E¸A±IÐ,>Ô?Ø˜‘
‘ð
	ð ˜*Ð&:Ð:Ð:Ø”$”tœC‘y &Ó)¨4Ð/Ð/r-   r®   c                 ób  — g g g }}}|D �]  \  }}| j                  «       dkD  rˆ|j                  | dd…||…f   j                  d¬«      d   «       |j                  |dd…||…f   j                  d¬«      d   «       |j                  |dd…||…f   j                  d¬«      d   «       Œ¢|j                  | || j                  «       «       |j                  ||| j                  «       «       |j                  ||| j                  «       «       �Œ
 | j                  «       dkD  rFt        j                  |d¬«      } t        j                  |d¬«      }t        j                  |d¬«      }n?t        j                  |«      } t        j                  |«      }t        j                  |«      }| ||fS )a)  Postprocesses metrics when dealing with multiple references.

    For each group of references that correspond to a single prediction,
    this function takes the maximum score among all references.

    Args:
        precision: Tensor of precision scores
        recall: Tensor of recall scores
        f1_score: Tensor of F1 scores
        ref_group_boundaries: List of tuples (start, end) indicating the boundaries
                              of reference groups

    Returns:
        tuple: (precision, recall, f1_score) with updated metrics

    r>   Nr?   r   )r@   rK   r_   rC   r–   )	r\   rj   rn   r®   Úmax_precisionÚ
max_recallÚmax_f1ÚstartÚends	            r%   Ú _postprocess_multiple_referencesr»   2  s‰  € ð& )+¨B°˜v�:€Mà*ó 5‰
ˆˆsØ�=‰=‹?˜QÒØ× Ñ  ª1¨e°C¨i¨<Ñ!8×!<Ñ!<ÀÐ!<Ó!CÀAÑ!FÔGØ×Ñ˜f¢Q¨¨c¨	 \Ñ2×6Ñ6¸1Ð6Ó=¸aÑ@ÔAØ�M‰M˜(¢1 e¨C i <Ñ0×4Ñ4¸Ð4Ó;¸AÑ>Õ?à× Ñ  ¨5°Ð!5×!9Ñ!9Ó!;Ô<Ø×Ñ˜f U¨3Ð/×3Ñ3Ó5Ô6Ø�M‰M˜( 5¨Ð-×1Ñ1Ó3Ö4ð5ð ‡}�}ƒ˜ÒÜ—K‘K °1Ô5ˆ	Ü—‘˜Z¨QÔ/ˆÜ—;‘;˜v¨1Ô-‰ä—K‘K Ó.ˆ	Ü—‘˜ZÓ(ˆÜ—;‘;˜vÓ&ˆà�f˜hÐ&Ð&r-   Úuser_tokenizerÚ
max_lengthÚ
batch_sizeÚnum_threadsÚreturn_hashÚrescale_with_baselineÚ
truncationc                 óø  — d}t        | t        «      r| g} t        |t        «      r|g}t        | t        t        f«      st        | «      } t        |t        t        f«      st        |«      }t	        | «      t	        |«      k7  r#t        dt	        | «      › dt	        |«      › �«      ‚t        | t        «      r<t	        | «      dkD  r.t        |t        «      rt	        |«      dkD  rt        | |«      \  } }}t        |	t        «      st        d|	› d�«      ‚|rt        st        d«      ‚|€tt        st        d«      ‚|€t        d	t        › d�«       t        «       5  t        j                  |xs t        «      }t!        j                  |xs t        «      }ddd«       n|}|j#                  «        |j%                  |
«       	 t'        |j(                  d
«      rgt        |j(                  j*                  t,        «      rC|rL||j(                  j*                  kD  r3t        d|› d|› d|j(                  j*                  › �«      ‚t        d«       t1        d„ | |fD «       «      }t1        d„ | |fD «       «      }t1        d„ | |fD «       «      }|r6t        d«       dgdgdgdœ}|r|j3                  dt5        |||	«      i«       |S |rt7        ||||«      nd}|r,t9        |||	|¬«      }t9        | |||	|j:                  |¬«      }n7|r*t=        di |¤d|	i¤Ž}t=        di | ¤|	|j:                  dœ¤Ž}nt        d«      ‚t?        |||¬«      }t?        |||¬«      }tA        ||jB                  ||
|||	||«	      \  }} tA        ||jB                  ||
|||	||«	      \  }!}"|!|jD                  jF                     }!||jD                  jF                     }|"|jD                  jF                     }"| |jD                  jF                     } tI        |!||"| «      \  }#}$}%|�tK        |#|$|%|||«      \  }#}$}%|�tM        |#|$|%|«      \  }#}$}%|#|$|%dœ}|r|j3                  dt5        |||	«      i«       |S # 1 sw Y   �ŒÃxY w# t.        $ r t        d«       Y �Œ3w xY w)a2  `Bert_score Evaluating Text Generation`_ for text similirity matching.

    This metric 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`_.

    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_name_or_path: 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.
        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. his 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 of 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. It is used when the scores are rescaled with a baseline.
        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 maximum length.

    Returns:
        Python dictionary containing the keys ``precision``, ``recall`` and ``f1`` with corresponding values.

    Raises:
        ValueError:
            If ``len(preds) != len(target)``.
        ModuleNotFoundError:
            If `tqdm` package is required and not installed.
        ModuleNotFoundError:
            If ``transformers`` package is required and not installed.
        ValueError:
            If ``num_layer`` is larger than the number of the model layers.
        ValueError:
            If invalid input is provided.

    Example:
        >>> from pprint import pprint
        >>> from torchmetrics.functional.text.bert import bert_score
        >>> preds = ["hello there", "general kenobi"]
        >>> target = ["hello there", "master kenobi"]
        >>> pprint(bert_score(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.functional.text.bert import bert_score
        >>> preds = ["hello there", "general kenobi"]
        >>> target = [["hello there", "master kenobi"], ["hello there", "master kenobi"]]
        >>> pprint(bert_score(preds, target))
        {'f1': tensor([1.0000, 0.9961]), 'precision': tensor([1.0000, 0.9961]), 'recall': tensor([1.0000, 0.9961])}

    NzLExpected number of predicted and reference sentences to be the same, but gotz and r   z1Expected argument `idf` to be a boolean, but got ú.zcAn argument `verbose = True` requires `tqdm` package be installed. Install with `pip install tqdm`.z®`bert_score` metric with default models requires `transformers` package be installed. Either install with `pip install transformers>=4.4` or `pip install torchmetrics[text]`.z«The argument `model_name_or_path` was not specified while it is required when default `transformers` model are used.It is, therefore, used the default recommended model - Únum_hidden_layersznum_layers=z is forbidden for z. Please use num_layers <= zhModel config does not have `num_hidden_layers` as an integer attribute. Unable to validate `num_layers`.zXIt was not possible to retrieve the parameter `num_layers` from the model specification.c              3   ó\   K  — | ]$  }t        |t        «      xr t        |«      d k(  –— Œ& y­w©r   N)rŸ   r¦   r¬   ©r¢   Útexts     r%   r£   zbert_score.<locals>.<genexpr>  s'   è ø€ ÒaÈœ: d¬DÓ1ÒD´c¸$³iÀ1±nÓDÑaùs   ‚*,c              3   ó†   K  — | ]9  }t        |t        «      xr# t        |«      d kD  xr t        |d    t        «      –— Œ; y­wrÇ   )rŸ   r¦   r¬   r    rÈ   s     r%   r£   zbert_score.<locals>.<genexpr>  s<   è ø€ ò ØRVŒ
�4œÓÒM¤3 t£9¨q¡=ÒM´ZÀÀQÁÌÓ5MÓMñùs   ‚?Ac              3   óf   K  — | ])  }t        |t        «      xr t        |d    t        «      –— Œ+ y­w)r:   N)rŸ   Údictr   rÈ   s     r%   r£   zbert_score.<locals>.<genexpr>  s0   è ø€ ò ØMQŒ
�4œÓÒH¤:¨d°;Ñ.?ÄÓ#HÓHñùs   ‚/1z%Predictions and references are empty.rk   )r\   rj   Úf1Úhash)r6   rÂ   )r6   Ú
tokens_idfrÂ   r6   )r6   rÏ   r¤   )r¾   Únum_workersr,   )'rŸ   r    r¦   rÌ   r¬   rG   r´   Úboolr   ÚModuleNotFoundErrorr   r   r+   r&   r(   r*   r'   ÚevalÚtoÚhasattrÚconfigrÅ   ÚintÚAttributeErrorr¨   Úupdatert   r”   r   rÏ   r   r   rX   r½   ÚdatasetÚsorting_indicesro   r™   r»   )&rš   r›   rp   r4   r5   r2   r¼   r8   r7   r6   r3   r½   r¾   r¿   rÀ   r�   rÁ   ru   r„   rÂ   r®   Ú	tokenizerÚ_are_empty_listsÚ_are_valid_listsÚ_are_valid_tensorsÚoutput_dictr’   Útarget_datasetÚpreds_datasetÚtarget_loaderÚpreds_loaderrf   rh   re   rg   r\   rj   rn   s&                                         r%   r/   r/   ]  s  € ðN =AÐä�%œÔØ�ˆÜ�&œ#ÔØ�ˆÜ�eœd¤D˜\Ô*Ü�U“ˆÜ�fœt¤T˜lÔ+Ü�f“ˆä
ˆ5ƒz”S˜“[Ò ÜØZÜ�5‹zˆl˜%¤ F£˜}ð.ó
ð 	
ô
 �%œÔ¤3 u£:°¢>´jÀÌÔ6NÔSVÐW]ÓS^ÐabÒSbÜ.MÈeÐU[Ó.\Ñ+ˆˆvÐ+ä�cœ4Ô ÜÐLÈSÈEÐQRÐSÓTÐTá�Ü!Øqó
ð 	
ð €}Ý.Ü%ðlóð ð Ð%ÜðJäJXÐIYÐYZð\ôô
 !Ó"ñ 	TÜ%×5Ñ5Ð6HÒ6ZÌNÓ[ˆIÜ×-Ñ-Ð.@Ò.RÄNÓSˆE÷	Tð 	Tð #ˆ	Ø	‡J�J„LØ	‡H�HˆVÔðsÜ�5—<‘<Ð!4Ô5¼*ÀUÇ\Á\×EcÑEcÔehÔ:iÙ˜j¨5¯<©<×+IÑ+IÒIÜ Ø! * Ð-?Ð@RÐ?Sð T1Ø16·±×1OÑ1OÐ0PðRóð ô
 ð3ôô ÑaÐRWÐY_ÐQ`ÔaÓaÐÜñ Ø[`ÐbhÐZiôó Ðô ñ ØV[Ð]cÐUdôó Ðñ ÜÐ>Ô?à˜Ø�eØ�%ñC
ˆñ
 Ø×Ñ ¬	Ð2DÀjÐRUÓ(VÐWÔXØÐñ YnŒ~˜dÐ$6¸À|ÔTÐsw€Hñ Ü$ V¨Y¸
ÈÐXbÔcˆÜ#ØØØØØ%×0Ñ0Ø!ô
‰ñ 
Ü)Ñ<¨FÑ<¸Ò<ˆÜ(Ñ`¨5Ð`°cÀn×F_ÑF_Ó`‰äÐ2Ó3Ð3ä˜~¸*ÐR]Ô^€MÜ˜m¸
ÐP[Ô\€Lä*GØ�~×0Ñ0°%¸ÀÈZÐY\Ð^eÐgvó+Ñ'ÐÐ'ô )FØ�m×.Ñ.°°v¸zÈ:ÐWZÐ\cÐetó)Ñ%Ð�oð (¨×(<Ñ(<×(LÑ(LÑMÐØ)¨-×*?Ñ*?×*OÑ*OÑPÐà% l×&:Ñ&:×&JÑ&JÑK€OØ'¨×(=Ñ(=×(MÑ(MÑNÐä":ØÐ+¨_Ð>Nó#Ñ€Iˆv�xð ÐÜ&DØ�v˜x¨°:¸zó'
Ñ#ˆ	�6˜8ð Ð'Ü&FØ�v˜xÐ)=ó'
Ñ#ˆ	�6˜8ð
 ØØñ€Kñ
 Ø×Ñ˜F¤IÐ.@À*ÈcÓ$RÐSÔTØÐ÷E	Tñ 	Tûô( ò sÜÐq×rðsús   Å;QÆ=BQ! ÑQÑ!Q9Ñ8Q9)r   N)NNFFFN)NNF)ÚenNNN)NF)NNFNNNFFNi   é@   r   Frå   FNNF)>rx   r   r‡   Úcollections.abcr   r   Ú
contextlibr   Útypingr   r   r   r	   r
   r   r   rC   r   Útorch.nnr   Útorch.utils.datar   Ú4torchmetrics.functional.text.helper_embedding_metricr   r   r   r   r   r   r   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.checksr   r   Útorchmetrics.utilities.importsr   r   r&   r+   Útransformersr'   r(   r.   Ú__doctest_skip__r×   r    r3   rÑ   rÌ   rX   rd   ro   rt   rƒ   rŽ   r”   r™   r´   r»   r{   r/   r,   r-   r%   ú<module>rò      s$  ðó Û Û ß .Ý %ß D× DÑ Dã Ý Ý Ý '÷÷ ñ õ 2ß Wß [ð ð(˜X d™^ò (ó ð(ð !€á"ß5ó6ñ Ñ";Ð<ZÔ"[Ø(˜>Ñà$�~Ðð 26Ø $ØØØØOSñN!ØðN!àðN!ð ðN!ð �U˜3 §¡Ð,Ñ-Ñ.ð	N!ð
 ˜‘ðN!ð ðN!ð 
ðN!ð ðN!ð ˜h¨°°S¸&°[Ñ0AÐ'BÀFÐ'JÑKÑLðN!ð ˆ6�6ˆ>ÑóN!ðb)¨Vð )¸Sð )ÈVð )ÐX^ó )ð'Øð'Ø17ð'ØJPð'Ødjð'à
ˆ6�6˜6Ð!Ñ"ó'ñ6O (¨3¡-ð OÀHÈSÁMð OÐ_cð OÐpsó Oð
	.¨Sð 	.°Vó 	.ð2 Sð 2¨Vó 2ð  Ø(,Ø#'Ø"&ñ	Ø
ðà  ™ðð ˜C‘=ðð ˜3‘-ð	ð
 ˆfÑóð8 !%ØñIØðIàðIð ðIð ð	Ið
 ˜‘ðIð ðIð ˆ6�6˜6Ð!Ñ"óIð$+0Ø�‰9ð+0Ø" 5¨¨h°s©mÐ);Ñ#<Ñ=ð+0à
ˆ4�‰9�d˜3‘i ¨$¨u°S¸#°X©Ñ*?Ñ!@Ð@ÑAó+0ð\('Øð('Ø%ð('Ø17ð('ØOSÐTYÐZ]Ð_bÐZbÑTcÑOdð('à
ˆ6�6˜6Ð!Ñ"ó('ð\ )-Ø $ØØ"ØØOSØØØ15ØØØØØØ"'Ø#'Ø"&Øñ)qØ��h˜s‘m T¨#¨v¨+Ñ%6Ð6Ñ7ðqà�#�x ‘} h¨x¸©}Ñ&=¸tÀCÈÀKÑ?PÐPÑQðqð ! ™ðqð ˜‘ð	qð
 ðqð �FÑðqð ðqð ˜h¨°°S¸&°[Ñ0AÐ'BÀFÐ'JÑKÑLðqð ðqð 
ðqð �U˜3 §¡Ð,Ñ-Ñ.ðqð ðqð ðqð ðqð ðqð  ð!qð"  ð#qð$ ˜C‘=ð%qð& ˜3‘-ð'qð( ð)qð* 
ˆ#ˆu�V˜T %™[¨#Ð-Ñ.Ð
.Ñ/ô+qr-   