


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


_snake_case					:		Union[str, Any]      =    get_tests_dir("fixtures/test_sentencepiece.model")


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

_snake_case					:		str      =    250_004
_snake_case					:		Optional[Any]      =    250_020

@require_sentencepiece
@require_tokenizers
class     a		(__UpperCamelCase					,    unittest.TestCase				):




							"""simple docstring"""


							__UpperCAmelCase   :							Any					  =  MBartTokenizer
							__UpperCAmelCase   :							Optional[Any]					  =  MBartTokenizerFast
							__UpperCAmelCase   :							List[Any]					  =  True
							__UpperCAmelCase   :							int					  =  True

							def    __snake_case (							self	:  Tuple    )     ->   Optional[int]:
														super().setUp()

														# We have a SentencePiece fixture for testing
														__snake_case		:      Dict										=       MBartTokenizer(_lowerCAmelCase   ,     keep_accents=_lowerCAmelCase    )
														tokenizer.save_pretrained(self.tmpdirname    )

							def    __snake_case (							self	:  Dict    )     ->   int:
														__snake_case		:      Optional[Any]										=       MBartTokenizer(_lowerCAmelCase   ,     keep_accents=_lowerCAmelCase    )

														__snake_case		:      int										=       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 [285, 46, 10, 170, 382]]   ,     )

														__snake_case		:      Optional[int]										=       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",
														        "é",
														        ".",
														    ]   ,     )
														__snake_case		:      Tuple										=       tokenizer.convert_tokens_to_ids(_lowerCAmelCase    )
														self.assertListEqual(
														    _lowerCAmelCase   ,     [
														        value + tokenizer.fairseq_offset
														        for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
														        #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
														    ]   ,     )

														__snake_case		:      str										=       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    __snake_case (							self	:  Tuple    )     ->   int:
														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

														__snake_case		:      Any										=       (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})'    ):
																												__snake_case		:      List[str]										=       self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase   ,     **_lowerCAmelCase    )
																												__snake_case		:      List[Any]										=       self.tokenizer_class.from_pretrained(_lowerCAmelCase   ,     **_lowerCAmelCase    )

																												__snake_case		:      List[Any]										=       tempfile.mkdtemp()

																												__snake_case		:      Tuple										=       tokenizer_r.save_pretrained(_lowerCAmelCase    )
																												__snake_case		:      Dict										=       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    )    )
																												__snake_case		:      str										=       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
																												__snake_case		:      Union[str, Any]										=       tokenizer_r.from_pretrained(_lowerCAmelCase    )
																												__snake_case		:      Dict										=       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
																												__snake_case		:      List[str]										=       tempfile.mkdtemp()

																												__snake_case		:      Dict										=       tokenizer_r.save_pretrained(_lowerCAmelCase   ,     legacy_format=_lowerCAmelCase    )
																												__snake_case		:      List[str]										=       tokenizer_p.save_pretrained(_lowerCAmelCase    )

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

																												# Checks everything loads correctly in the same way
																												__snake_case		:      List[Any]										=       tokenizer_r.from_pretrained(_lowerCAmelCase    )
																												__snake_case		:      int										=       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
																												__snake_case		:      int										=       tempfile.mkdtemp()

																												__snake_case		:      List[Any]										=       tokenizer_r.save_pretrained(_lowerCAmelCase   ,     legacy_format=_lowerCAmelCase    )
																												__snake_case		:      List[str]										=       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
																												__snake_case		:      Union[str, Any]										=       tokenizer_r.from_pretrained(_lowerCAmelCase    )
																												__snake_case		:      Tuple										=       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"""


							__UpperCAmelCase   :							List[str]					  =  "facebook/mbart-large-en-ro"
							__UpperCAmelCase   :							Optional[Any]					  =  [
							    " 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.",
							]
							__UpperCAmelCase   :							Dict					  =  [
							    "Ş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.",
							]
							__UpperCAmelCase   :							Tuple					  =  [8274, 12_7873, 2_5916, 7, 8622, 2071, 438, 6_7485, 53, 18_7895, 23, 5_1712, 2, EN_CODE]

							@classmethod
							def    __snake_case (							cls	:  Tuple    )     ->   List[str]:
														__snake_case		:      MBartTokenizer										=       MBartTokenizer.from_pretrained(
														    cls.checkpoint_name   ,     src_lang="en_XX"   ,     tgt_lang="ro_RO"    )
														__snake_case		:      Optional[int]										=       1
														return cls

							def    __snake_case (							self	:  Union[str, Any]    )     ->   str:
														self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"]   ,     250001    )
														self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"]   ,     250004    )
														self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"]   ,     250020    )

							def    __snake_case (							self	:  Dict    )     ->   Any:
														__snake_case		:      Any										=       self.tokenizer.batch_encode_plus(self.src_text    ).input_ids[0]
														self.assertListEqual(self.expected_src_tokens   ,     _lowerCAmelCase    )

							def    __snake_case (							self	:  str    )     ->   Dict:
														self.assertIn(_lowerCAmelCase   ,     self.tokenizer.all_special_ids    )
														__snake_case		:      Optional[Any]										=       [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2]
														__snake_case		:      int										=       self.tokenizer.decode(_lowerCAmelCase   ,     skip_special_tokens=_lowerCAmelCase    )
														__snake_case		:      Any										=       self.tokenizer.decode(generated_ids[1:]   ,     skip_special_tokens=_lowerCAmelCase    )
														self.assertEqual(_lowerCAmelCase   ,     _lowerCAmelCase    )
														self.assertNotIn(self.tokenizer.eos_token   ,     _lowerCAmelCase    )

							def    __snake_case (							self	:  int    )     ->   Tuple:
														__snake_case		:      Tuple										=       ["""this is gunna be a long sentence """ * 20]
														assert isinstance(src_text[0]   ,     _lowerCAmelCase    )
														__snake_case		:      Optional[Any]										=       10
														__snake_case		:      Dict										=       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    __snake_case (							self	:  Any    )     ->   int:
														self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"]    )   ,     [250026, 250001]    )

							def    __snake_case (							self	:  List[Any]    )     ->   Tuple:
														__snake_case		:      Union[str, Any]										=       tempfile.mkdtemp()
														__snake_case		:      List[Any]										=       self.tokenizer.fairseq_tokens_to_ids
														self.tokenizer.save_pretrained(_lowerCAmelCase    )
														__snake_case		:      Any										=       MBartTokenizer.from_pretrained(_lowerCAmelCase    )
														self.assertDictEqual(new_tok.fairseq_tokens_to_ids   ,     _lowerCAmelCase    )

							@require_torch
							def    __snake_case (							self	:  Dict    )     ->   Any:
														__snake_case		:      Optional[Any]										=       self.tokenizer(self.src_text   ,     text_target=self.tgt_text   ,     padding=_lowerCAmelCase   ,     return_tensors="pt"    )
														__snake_case		:      Optional[int]										=       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    __snake_case (							self	:  Optional[int]    )     ->   str:
														__snake_case		:      Optional[Any]										=       self.tokenizer(
														    self.src_text   ,     text_target=self.tgt_text   ,     padding=_lowerCAmelCase   ,     truncation=_lowerCAmelCase   ,     max_length=len(self.expected_src_tokens    )   ,     return_tensors="pt"   ,     )

														__snake_case		:      Any										=       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    )
														__snake_case		:      List[Any]										=       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    __snake_case (							self	:  Tuple    )     ->   Optional[int]:
														__snake_case		:      Union[str, Any]										=       self.tokenizer(self.src_text   ,     padding=_lowerCAmelCase   ,     truncation=_lowerCAmelCase   ,     max_length=3   ,     return_tensors="pt"    )
														__snake_case		:      List[str]										=       self.tokenizer(
														    text_target=self.tgt_text   ,     padding=_lowerCAmelCase   ,     truncation=_lowerCAmelCase   ,     max_length=10   ,     return_tensors="pt"    )
														__snake_case		:      Union[str, Any]										=       targets["""input_ids"""]
														__snake_case		:      Tuple										=       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    __snake_case (							self	:  List[str]    )     ->   Optional[Any]:
														__snake_case		:      Any										=       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, 3034, 2, 250004]],
														        "attention_mask": [[1, 1, 1, 1]],
														        # ar_AR
														        "forced_bos_token_id": 250001,
														    }   ,     )





from scipy.stats import spearmanr

import datasets


_snake_case					:		Optional[Any]      =    "\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n"

_snake_case					:		Dict      =    "\nArgs:\n    predictions (`List[float]`): Predicted labels, as returned by a model.\n    references (`List[float]`): Ground truth labels.\n    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n            only the spearmanr score. Defaults to `False`.\nReturns:\n    spearmanr (`float`): Spearman correlation coefficient.\n    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n    Example 1:\n        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n        >>> print(results)\n        {'spearmanr': -0.7}\n\n    Example 2:\n        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n        ...                                     predictions=[10, 9, 2.5, 6, 4],\n        ...                                     return_pvalue=True)\n        >>> print(results['spearmanr'])\n        -0.7\n        >>> print(round(results['spearmanr_pvalue'], 2))\n        0.19\n"

_snake_case					:		Optional[Any]      =    R"\\n@book{kokoska2000crc,\n  title={CRC standard probability and statistics tables and formulae},\n  author={Kokoska, Stephen and Zwillinger, Daniel},\n  year={2000},\n  publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n            Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n            Kern, Robert and Larson, Eric and Carey, C J and\n            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n            Harris, Charles R. and Archibald, Anne M. and\n            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n            Computing in Python}},\n  journal = {Nature Methods},\n  year    = {2020},\n  volume  = {17},\n  pages   = {261--272},\n  adsurl  = {https://rdcu.be/b08Wh},\n  doi     = {10.1038/s41592-019-0686-2},\n}\n"

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,    _KWARGS_DESCRIPTION				)
class     a		(datasets.Metric				):




							"""simple docstring"""


							def    __snake_case (							self	:  Optional[int]    )     ->   Any:
														return datasets.MetricInfo(
														    description=_DESCRIPTION   ,     citation=_CITATION   ,     inputs_description=_KWARGS_DESCRIPTION   ,     features=datasets.Features(
														        {
														            "predictions": datasets.Value("float"    ),
														            "references": datasets.Value("float"    ),
														        }    )   ,     reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"]   ,     )






							def    __snake_case (							self	:  Optional[Any]   ,     lowerCamelCase	:  Optional[int]   ,     lowerCamelCase	:  int   ,     lowerCamelCase	:  Tuple=False    )     ->   Dict:
														__snake_case		:      Optional[int]										=       spearmanr(lowerCamelCase   ,     lowerCamelCase    )
														if return_pvalue:
																					return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
														else:
																					return {"spearmanr": results[0]}

