





import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


A    :					str =      get_tests_dir('''fixtures/test_sentencepiece.model''')


if is_torch_available():
					from transformers.models.mbart.modeling_mbart import shift_tokens_right

A    :					Union[str, Any] =      2_5_0_0_0_4
A    :					List[str] =      2_5_0_0_2_0


@require_sentencepiece
@require_tokenizers
class   A			(SCREAMING_SNAKE_CASE   ,     unittest.TestCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       Dict							=    MBartTokenizer
			__lowerCamelCase	:       Tuple							=    MBartTokenizerFast
			__lowerCamelCase	:       Any							=    True
			__lowerCamelCase	:       Any							=    True






			def    a_       (			self   :    Union[str, Any]   )	->	Optional[Any]:







					"""simple docstring"""






					super().setUp()

					# We have a SentencePiece fixture for testing
					A__        =   MBartTokenizer(__lowerCAmelCase							,	keep_accents=__lowerCAmelCase   )
					tokenizer.save_pretrained(self.tmpdirname   )






			def    a_       (			self   :    List[str]   )	->	Dict:







					"""simple docstring"""






					A__        =   MBartTokenizer(__lowerCAmelCase							,	keep_accents=__lowerCAmelCase   )

					A__        =   tokenizer.tokenize("""This is a test"""   )
					self.assertListEqual(__lowerCAmelCase							,	["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]   )

					self.assertListEqual(
					    tokenizer.convert_tokens_to_ids(__lowerCAmelCase   )							,	[value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]]							,	)

					A__        =   tokenizer.tokenize("""I was born in 92000, and this is falsé."""   )
					self.assertListEqual(
					    __lowerCAmelCase							,	[
					        SPIECE_UNDERLINE + """I""",
					        SPIECE_UNDERLINE + """was""",
					        SPIECE_UNDERLINE + """b""",
					        """or""",
					        """n""",
					        SPIECE_UNDERLINE + """in""",
					        SPIECE_UNDERLINE + """""",
					        """9""",
					        """2""",
					        """0""",
					        """0""",
					        """0""",
					        """,""",
					        SPIECE_UNDERLINE + """and""",
					        SPIECE_UNDERLINE + """this""",
					        SPIECE_UNDERLINE + """is""",
					        SPIECE_UNDERLINE + """f""",
					        """al""",
					        """s""",
					        """é""",
					        """.""",
					    ]							,	)
					A__        =   tokenizer.convert_tokens_to_ids(__lowerCAmelCase   )
					self.assertListEqual(
					    __lowerCAmelCase							,	[
					        value + tokenizer.fairseq_offset
					        for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4]
					        #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
					    ]							,	)

					A__        =   tokenizer.convert_ids_to_tokens(__lowerCAmelCase   )
					self.assertListEqual(
					    __lowerCAmelCase							,	[
					        SPIECE_UNDERLINE + """I""",
					        SPIECE_UNDERLINE + """was""",
					        SPIECE_UNDERLINE + """b""",
					        """or""",
					        """n""",
					        SPIECE_UNDERLINE + """in""",
					        SPIECE_UNDERLINE + """""",
					        """<unk>""",
					        """2""",
					        """0""",
					        """0""",
					        """0""",
					        """,""",
					        SPIECE_UNDERLINE + """and""",
					        SPIECE_UNDERLINE + """this""",
					        SPIECE_UNDERLINE + """is""",
					        SPIECE_UNDERLINE + """f""",
					        """al""",
					        """s""",
					        """<unk>""",
					        """.""",
					    ]							,	)







			def    a_       (			self   :    str   )	->	Any:







					"""simple docstring"""






					if not self.test_slow_tokenizer:
							# as we don't have a slow version, we can't compare the outputs between slow and fast versions
							return

					A__        =   (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {})
					for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
							with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'   ):
									A__        =   self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase							,	**__lowerCAmelCase   )
									A__        =   self.tokenizer_class.from_pretrained(__lowerCAmelCase							,	**__lowerCAmelCase   )

									A__        =   tempfile.mkdtemp()

									A__        =   tokenizer_r.save_pretrained(__lowerCAmelCase   )
									A__        =   tokenizer_p.save_pretrained(__lowerCAmelCase   )

									# Checks it save with the same files + the tokenizer.json file for the fast one
									self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files   )   )
									A__        =   tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f   )
									self.assertSequenceEqual(__lowerCAmelCase							,	__lowerCAmelCase   )

									# Checks everything loads correctly in the same way
									A__        =   tokenizer_r.from_pretrained(__lowerCAmelCase   )
									A__        =   tokenizer_p.from_pretrained(__lowerCAmelCase   )

									# Check special tokens are set accordingly on Rust and Python
									for key in tokenizer_pp.special_tokens_map:
											self.assertTrue(hasattr(__lowerCAmelCase							,	__lowerCAmelCase   )   )
											# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
											# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

									shutil.rmtree(__lowerCAmelCase   )

									# Save tokenizer rust, legacy_format=True
									A__        =   tempfile.mkdtemp()

									A__        =   tokenizer_r.save_pretrained(__lowerCAmelCase							,	legacy_format=__lowerCAmelCase   )
									A__        =   tokenizer_p.save_pretrained(__lowerCAmelCase   )

									# Checks it save with the same files
									self.assertSequenceEqual(__lowerCAmelCase							,	__lowerCAmelCase   )

									# Checks everything loads correctly in the same way
									A__        =   tokenizer_r.from_pretrained(__lowerCAmelCase   )
									A__        =   tokenizer_p.from_pretrained(__lowerCAmelCase   )

									# Check special tokens are set accordingly on Rust and Python
									for key in tokenizer_pp.special_tokens_map:
											self.assertTrue(hasattr(__lowerCAmelCase							,	__lowerCAmelCase   )   )

									shutil.rmtree(__lowerCAmelCase   )

									# Save tokenizer rust, legacy_format=False
									A__        =   tempfile.mkdtemp()

									A__        =   tokenizer_r.save_pretrained(__lowerCAmelCase							,	legacy_format=__lowerCAmelCase   )
									A__        =   tokenizer_p.save_pretrained(__lowerCAmelCase   )

									# Checks it saved the tokenizer.json file
									self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files   )   )

									# Checks everything loads correctly in the same way
									A__        =   tokenizer_r.from_pretrained(__lowerCAmelCase   )
									A__        =   tokenizer_p.from_pretrained(__lowerCAmelCase   )

									# Check special tokens are set accordingly on Rust and Python
									for key in tokenizer_pp.special_tokens_map:
											self.assertTrue(hasattr(__lowerCAmelCase							,	__lowerCAmelCase   )   )

									shutil.rmtree(__lowerCAmelCase   )


@require_torch
@require_sentencepiece
@require_tokenizers
class   A			(unittest.TestCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       Dict							=    '''facebook/mbart-large-en-ro'''
			__lowerCamelCase	:       Dict							=    [
			    ''' UN Chief Says There Is No Military Solution in Syria''',
			    ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''',
			]
			__lowerCamelCase	:       Tuple							=    [
			    '''Şeful ONU declară că nu există o soluţie militară în Siria''',
			    '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei'''
			    ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'''
			    ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''',
			]
			__lowerCamelCase	:       Tuple							=    [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE]






			@classmethod
			def    a_       (			cls   :    Any   )	->	str:







					"""simple docstring"""






					A__        =   MBartTokenizer.from_pretrained(
					    cls.checkpoint_name							,	src_lang="""en_XX"""							,	tgt_lang="""ro_RO"""   )
					A__        =   1
					return cls






			def    a_       (			self   :    Dict   )	->	Dict:







					"""simple docstring"""






					self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""]							,	25_00_01   )
					self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""]							,	25_00_04   )
					self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""]							,	25_00_20   )






			def    a_       (			self   :    Optional[int]   )	->	Any:







					"""simple docstring"""






					A__        =   self.tokenizer.batch_encode_plus(self.src_text   ).input_ids[0]
					self.assertListEqual(self.expected_src_tokens							,	__lowerCAmelCase   )






			def    a_       (			self   :    str   )	->	Dict:







					"""simple docstring"""






					self.assertIn(__lowerCAmelCase							,	self.tokenizer.all_special_ids   )
					A__        =   [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2]
					A__        =   self.tokenizer.decode(__lowerCAmelCase							,	skip_special_tokens=__lowerCAmelCase   )
					A__        =   self.tokenizer.decode(generated_ids[1:]							,	skip_special_tokens=__lowerCAmelCase   )
					self.assertEqual(__lowerCAmelCase							,	__lowerCAmelCase   )
					self.assertNotIn(self.tokenizer.eos_token							,	__lowerCAmelCase   )






			def    a_       (			self   :    Any   )	->	Tuple:







					"""simple docstring"""






					A__        =   ["""this is gunna be a long sentence """ * 20]
					assert isinstance(src_text[0]							,	__lowerCAmelCase   )
					A__        =   10
					A__        =   self.tokenizer(__lowerCAmelCase							,	max_length=__lowerCAmelCase							,	truncation=__lowerCAmelCase   ).input_ids[0]
					self.assertEqual(ids[-2]							,	2   )
					self.assertEqual(ids[-1]							,	__lowerCAmelCase   )
					self.assertEqual(len(__lowerCAmelCase   )							,	__lowerCAmelCase   )






			def    a_       (			self   :    Dict   )	->	Any:







					"""simple docstring"""






					self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""]   )							,	[25_00_26, 25_00_01]   )






			def    a_       (			self   :    Optional[int]   )	->	Union[str, Any]:







					"""simple docstring"""






					A__        =   tempfile.mkdtemp()
					A__        =   self.tokenizer.fairseq_tokens_to_ids
					self.tokenizer.save_pretrained(__lowerCAmelCase   )
					A__        =   MBartTokenizer.from_pretrained(__lowerCAmelCase   )
					self.assertDictEqual(new_tok.fairseq_tokens_to_ids							,	__lowerCAmelCase   )






			@require_torch
			def    a_       (			self   :    List[Any]   )	->	int:







					"""simple docstring"""






					A__        =   self.tokenizer(self.src_text							,	text_target=self.tgt_text							,	padding=__lowerCAmelCase							,	return_tensors="""pt"""   )
					A__        =   shift_tokens_right(batch["""labels"""]							,	self.tokenizer.pad_token_id   )

					# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
					assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
					assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
					assert batch.decoder_input_ids[1][-1] == 2
					assert batch.labels[1][-2:].tolist() == [2, RO_CODE]






			@require_torch
			def    a_       (			self   :    List[Any]   )	->	Any:







					"""simple docstring"""






					A__        =   self.tokenizer(
					    self.src_text							,	text_target=self.tgt_text							,	padding=__lowerCAmelCase							,	truncation=__lowerCAmelCase							,	max_length=len(self.expected_src_tokens   )							,	return_tensors="""pt"""							,	)

					A__        =   shift_tokens_right(batch["""labels"""]							,	self.tokenizer.pad_token_id   )

					self.assertIsInstance(__lowerCAmelCase							,	__lowerCAmelCase   )

					self.assertEqual((2, 14)							,	batch.input_ids.shape   )
					self.assertEqual((2, 14)							,	batch.attention_mask.shape   )
					A__        =   batch.input_ids.tolist()[0]
					self.assertListEqual(self.expected_src_tokens							,	__lowerCAmelCase   )
					self.assertEqual(2							,	batch.decoder_input_ids[0, -1]   )  # EOS
					# Test that special tokens are reset
					self.assertEqual(self.tokenizer.prefix_tokens							,	[]   )
					self.assertEqual(self.tokenizer.suffix_tokens							,	[self.tokenizer.eos_token_id, EN_CODE]   )






			def    a_       (			self   :    List[Any]   )	->	List[Any]:







					"""simple docstring"""






					A__        =   self.tokenizer(self.src_text							,	padding=__lowerCAmelCase							,	truncation=__lowerCAmelCase							,	max_length=3							,	return_tensors="""pt"""   )
					A__        =   self.tokenizer(
					    text_target=self.tgt_text							,	padding=__lowerCAmelCase							,	truncation=__lowerCAmelCase							,	max_length=10							,	return_tensors="""pt"""   )
					A__        =   targets["""input_ids"""]
					A__        =   shift_tokens_right(__lowerCAmelCase							,	self.tokenizer.pad_token_id   )

					self.assertEqual(batch.input_ids.shape[1]							,	3   )
					self.assertEqual(batch.decoder_input_ids.shape[1]							,	10   )







			@require_torch
			def    a_       (			self   :    int   )	->	Any:







					"""simple docstring"""






					A__        =   self.tokenizer._build_translation_inputs(
					    """A test"""							,	return_tensors="""pt"""							,	src_lang="""en_XX"""							,	tgt_lang="""ar_AR"""   )

					self.assertEqual(
					    nested_simplify(__lowerCAmelCase   )							,	{
					        # A, test, EOS, en_XX
					        """input_ids""": [[62, 30_34, 2, 25_00_04]],
					        """attention_mask""": [[1, 1, 1, 1]],
					        # ar_AR
					        """forced_bos_token_id""": 25_00_01,
					    }							,	)










from sklearn.metrics import fa_score

import datasets


A    :					Any =      '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


A    :					List[Any] =      '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


A    :					List[Any] =      '''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,     _KWARGS_DESCRIPTION    )
class   A			(datasets.Metric    ):
			'''simple docstring'''




			def    a_       (			self   :    Optional[int]   )	->	List[Any]:







					"""simple docstring"""






					return datasets.MetricInfo(
					    description=_DESCRIPTION							,	citation=_CITATION							,	inputs_description=_KWARGS_DESCRIPTION							,	features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					            """references""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					        }
					        if self.config_name == """multilabel"""
					        else {
					            """predictions""": datasets.Value("""int32"""   ),
					            """references""": datasets.Value("""int32"""   ),
					        }   )							,	reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"""]							,	)







			def    a_       (			self   :    Any							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Dict=None							,	__lowerCAmelCase   :    List[str]=1							,	__lowerCAmelCase   :    Any="binary"							,	__lowerCAmelCase   :    Optional[int]=None   )	->	List[Any]:







					"""simple docstring"""






					A__        =   fa_score(
					    __lowerCAmelCase							,	__lowerCAmelCase							,	labels=__lowerCAmelCase							,	pos_label=__lowerCAmelCase							,	average=__lowerCAmelCase							,	sample_weight=__lowerCAmelCase   )
					return {"f1": float(__lowerCAmelCase   ) if score.size == 1 else score}



