





import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
    __lowerCamelCase	:					Optional[Any]			  =					"""pt"""
elif is_tf_available():
    __lowerCamelCase	:					str			  =					"""tf"""
else:
    __lowerCamelCase	:					Any			  =					"""jax"""



class  A__       (	__snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :Optional[Any]						   =       ByTaTokenizer
      _UpperCAmelCase     :Union[str, Any]						   =       False





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       super().setUp()
       UpperCamelCase     : Any	     =       ByTaTokenizer()
       tokenizer.save_pretrained(self.tmpdirname       )





      @cached_property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return ByTaTokenizer.from_pretrained("google/byt5-small"       )





      def 	__UpperCamelCase(			self	,							**A_       ):
       '''simple docstring'''




       return self.tokenizer_class.from_pretrained(self.tmpdirname	,							**A_       )





      def 	__UpperCamelCase(			self	,							A_	,							A_=False	,							A_=20	,							A_=5       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       []
       for i in range(len(A_       )       ):
        try:
         UpperCamelCase     : Any	     =       tokenizer.decode([i]	,							clean_up_tokenization_spaces=A_       )
        except UnicodeDecodeError:
         pass
        toks.append((i, tok)       )

       UpperCamelCase     : Tuple	     =       list(filter(lambda A_       : re.match(R"^[ a-zA-Z]+$"	,							t[1]       )	,							A_       )       )
       UpperCamelCase     : Any	     =       list(filter(lambda A_       : [t[0]] == tokenizer.encode(t[1]	,							add_special_tokens=A_       )	,							A_       )       )
       if max_length is not None and len(A_       ) > max_length:
        UpperCamelCase     : Any	     =       toks[:max_length]
       if min_length is not None and len(A_       ) < min_length and len(A_       ) > 0:
        while len(A_       ) < min_length:
         UpperCamelCase     : Dict	     =       toks + toks
        # toks_str = [t[1] for t in toks]
       UpperCamelCase     : Any	     =       [t[0] for t in toks]

       # Ensure consistency
       UpperCamelCase     : Any	     =       tokenizer.decode(A_	,							clean_up_tokenization_spaces=A_       )
       if " " not in output_txt and len(A_       ) > 1:
        UpperCamelCase     : Optional[Any]	     =       (
            tokenizer.decode([toks_ids[0]]	,							clean_up_tokenization_spaces=A_       )
            + " "
            + tokenizer.decode(toks_ids[1:]	,							clean_up_tokenization_spaces=A_       )
        )
       if with_prefix_space:
        UpperCamelCase     : Any	     =       " " + output_txt
       UpperCamelCase     : List[Any]	     =       tokenizer.encode(A_	,							add_special_tokens=A_       )
       return output_txt, output_ids





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.ta_base_tokenizer
       UpperCamelCase     : Any	     =       tokenizer(["hi</s>", "I went to the gym</s>", "</s>"]       )
       UpperCamelCase     : Any	     =       tokenizer(["hi", "I went to the gym", ""]       )
       self.assertListEqual(batch_with_eos_added["input_ids"]	,							batch_without_eos_added["input_ids"]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       self.ta_base_tokenizer
       UpperCamelCase     : Optional[int]	     =       "Unicode €."
       UpperCamelCase     : Dict	     =       tokenizer(A_       )
       UpperCamelCase     : Tuple	     =       [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
       self.assertEqual(encoded["input_ids"]	,							A_       )

       # decoding
       UpperCamelCase     : int	     =       tokenizer.decode(A_       )
       self.assertEqual(A_	,							"Unicode €.</s>"       )

       UpperCamelCase     : Tuple	     =       tokenizer("e è é ê ë"       )
       UpperCamelCase     : int	     =       [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
       self.assertEqual(encoded["input_ids"]	,							A_       )
       # decoding
       UpperCamelCase     : Optional[int]	     =       tokenizer.decode(A_       )
       self.assertEqual(A_	,							"e è é ê ë</s>"       )

       # encode/decode, but with `encode` instead of `__call__`
       self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë"       )       )	,							"e è é ê ë</s>"       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : List[Any]	     =       self.ta_base_tokenizer
       UpperCamelCase     : List[str]	     =       ["A long paragraph for summarization.", "Another paragraph for summarization."]
       # fmt: off
       UpperCamelCase     : Union[str, Any]	     =       [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0]
       # fmt: on
       UpperCamelCase     : Optional[Any]	     =       tokenizer(A_	,							padding=A_	,							return_tensors=A_       )
       self.assertIsInstance(A_	,							A_       )

       if FRAMEWORK != "jax":
        UpperCamelCase     : Optional[int]	     =       list(batch.input_ids.numpy()[0]       )
       else:
        UpperCamelCase     : List[Any]	     =       list(batch.input_ids.tolist()[0]       )

       self.assertListEqual(A_	,							A_       )

       self.assertEqual((2, 37)	,							batch.input_ids.shape       )
       self.assertEqual((2, 37)	,							batch.attention_mask.shape       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.ta_base_tokenizer
       UpperCamelCase     : Optional[int]	     =       ["A long paragraph for summarization.", "Another paragraph for summarization."]
       UpperCamelCase     : Union[str, Any]	     =       tokenizer(A_	,							padding=A_	,							return_tensors=A_       )
       # check if input_ids are returned and no decoder_input_ids
       self.assertIn("input_ids"	,							A_       )
       self.assertIn("attention_mask"	,							A_       )
       self.assertNotIn("decoder_input_ids"	,							A_       )
       self.assertNotIn("decoder_attention_mask"	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       self.ta_base_tokenizer
       UpperCamelCase     : Optional[Any]	     =       [
           "Summary of the text.",
           "Another summary.",
       ]
       UpperCamelCase     : str	     =       tokenizer(
           text_target=A_	,							max_length=32	,							padding="max_length"	,							truncation=A_	,							return_tensors=A_       )
       self.assertEqual(32	,							targets["input_ids"].shape[1]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       self.ta_base_tokenizer
       UpperCamelCase     : Optional[Any]	     =       ["A long paragraph for summarization. </s>"]
       UpperCamelCase     : List[str]	     =       ["Summary of the text. </s>"]
       # fmt: off
       UpperCamelCase     : List[Any]	     =       [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1]
       UpperCamelCase     : Dict	     =       [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1]
       # fmt: on

       UpperCamelCase     : Dict	     =       tokenizer(A_	,							text_target=A_       )

       self.assertEqual(A_	,							batch["input_ids"][0]       )
       self.assertEqual(A_	,							batch["labels"][0]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.get_tokenizers()
       for tokenizer in tokenizers:
        with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
         self.assertNotEqual(tokenizer.model_max_length	,							42       )

        # Now let's start the test
       UpperCamelCase     : str	     =       self.get_tokenizers()
       for tokenizer in tokenizers:
        with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
         # Isolate this from the other tests because we save additional tokens/etc
         UpperCamelCase     : Tuple	     =       tempfile.mkdtemp()

         UpperCamelCase     : int	     =       " He is very happy, UNwant\u00E9d,running"
         UpperCamelCase     : str	     =       tokenizer.encode(A_	,							add_special_tokens=A_       )
         tokenizer.save_pretrained(A_       )

         UpperCamelCase     : Union[str, Any]	     =       tokenizer.__class__.from_pretrained(A_       )
         UpperCamelCase     : Any	     =       after_tokenizer.encode(A_	,							add_special_tokens=A_       )
         self.assertListEqual(A_	,							A_       )

         shutil.rmtree(A_       )

       UpperCamelCase     : int	     =       self.get_tokenizers(model_max_length=42       )
       for tokenizer in tokenizers:
        with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
         # Isolate this from the other tests because we save additional tokens/etc
         UpperCamelCase     : Optional[int]	     =       tempfile.mkdtemp()

         UpperCamelCase     : Optional[int]	     =       " He is very happy, UNwant\u00E9d,running"
         tokenizer.add_tokens(["bim", "bambam"]       )
         UpperCamelCase     : Optional[int]	     =       tokenizer.additional_special_tokens
         additional_special_tokens.append("new_additional_special_token"       )
         tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}       )
         UpperCamelCase     : List[str]	     =       tokenizer.encode(A_	,							add_special_tokens=A_       )
         tokenizer.save_pretrained(A_       )

         UpperCamelCase     : Any	     =       tokenizer.__class__.from_pretrained(A_       )
         UpperCamelCase     : Dict	     =       after_tokenizer.encode(A_	,							add_special_tokens=A_       )
         self.assertListEqual(A_	,							A_       )
         self.assertIn("new_additional_special_token"	,							after_tokenizer.additional_special_tokens       )
         self.assertEqual(after_tokenizer.model_max_length	,							42       )

         UpperCamelCase     : Optional[Any]	     =       tokenizer.__class__.from_pretrained(A_	,							model_max_length=43       )
         self.assertEqual(tokenizer.model_max_length	,							43       )

         shutil.rmtree(A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       []
       if self.test_slow_tokenizer:
        tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())       )

       if self.test_rust_tokenizer:
        tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())       )

       for tokenizer_class, tokenizer_utils in tokenizer_list:
        with tempfile.TemporaryDirectory() as tmp_dir:
         tokenizer_utils.save_pretrained(A_       )

         with open(os.path.join(A_	,							"special_tokens_map.json"       )	,							encoding="utf-8"       ) as json_file:
          UpperCamelCase     : Dict	     =       json.load(A_       )

         with open(os.path.join(A_	,							"tokenizer_config.json"       )	,							encoding="utf-8"       ) as json_file:
          UpperCamelCase     : Dict	     =       json.load(A_       )

         UpperCamelCase     : Tuple	     =       [F"""<extra_id_{i}>""" for i in range(125       )]

         UpperCamelCase     : Any	     =       added_tokens_extra_ids + [
             "an_additional_special_token"
         ]
         UpperCamelCase     : List[Any]	     =       added_tokens_extra_ids + [
             "an_additional_special_token"
         ]

         with open(os.path.join(A_	,							"special_tokens_map.json"       )	,							"w"	,							encoding="utf-8"       ) as outfile:
          json.dump(A_	,							A_       )
         with open(os.path.join(A_	,							"tokenizer_config.json"       )	,							"w"	,							encoding="utf-8"       ) as outfile:
          json.dump(A_	,							A_       )

         # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
         # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
         # "special_tokens_map.json" files
         UpperCamelCase     : Tuple	     =       tokenizer_class.from_pretrained(
             A_	,							)
         self.assertIn(
             "an_additional_special_token"	,							tokenizer_without_change_in_init.additional_special_tokens       )
         # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
         self.assertEqual(
             ["an_additional_special_token"]	,							tokenizer_without_change_in_init.convert_ids_to_tokens(
                 tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"]       )       )	,							)

         # Now we test that we can change the value of additional_special_tokens in the from_pretrained
         UpperCamelCase     : Dict	     =       added_tokens_extra_ids + [AddedToken("a_new_additional_special_token"	,							lstrip=A_       )]
         UpperCamelCase     : Union[str, Any]	     =       tokenizer_class.from_pretrained(
             A_	,							additional_special_tokens=A_	,							)

         self.assertIn("a_new_additional_special_token"	,							tokenizer.additional_special_tokens       )
         self.assertEqual(
             ["a_new_additional_special_token"]	,							tokenizer.convert_ids_to_tokens(
                 tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"]       )       )	,							)





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       []
       if self.test_slow_tokenizer:
        tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())       )

       if self.test_rust_tokenizer:
        tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())       )

       for tokenizer_class, tokenizer_utils in tokenizer_list:
        with tempfile.TemporaryDirectory() as tmp_dir:
         tokenizer_utils.save_pretrained(A_       )

         UpperCamelCase     : List[Any]	     =       tokenizer_class.from_pretrained(A_       )

         self.assertTrue(tokenizer.decode([255]       ) == ""       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.get_tokenizers(fast=A_	,							do_lower_case=A_       )
       for tokenizer in tokenizers:
        with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
         UpperCamelCase     : str	     =       ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"]
         UpperCamelCase     : Union[str, Any]	     =       tokenizer.convert_tokens_to_string(A_       )

         self.assertIsInstance(A_	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.get_tokenizers()
       for tokenizer in tokenizers:
        with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
         UpperCamelCase     : Optional[int]	     =       [
             "bos_token",
             "eos_token",
             "unk_token",
             "sep_token",
             "pad_token",
             "cls_token",
             "mask_token",
         ]

         UpperCamelCase     : Union[str, Any]	     =       0
         UpperCamelCase     : List[Any]	     =       tokenizer.convert_ids_to_tokens(
             A_	,							skip_special_tokens=A_       )

         for attr in attributes_list:
          setattr(A_	,							attr + "_id"	,							A_       )
          self.assertEqual(getattr(A_	,							A_       )	,							A_       )
          self.assertEqual(getattr(A_	,							attr + "_id"       )	,							A_       )

          setattr(A_	,							attr + "_id"	,							A_       )
          self.assertEqual(getattr(A_	,							A_       )	,							A_       )
          self.assertEqual(getattr(A_	,							attr + "_id"       )	,							A_       )

         setattr(A_	,							"additional_special_tokens_ids"	,							[]       )
         self.assertListEqual(getattr(A_	,							"additional_special_tokens"       )	,							[]       )
         self.assertListEqual(getattr(A_	,							"additional_special_tokens_ids"       )	,							[]       )

         setattr(A_	,							"additional_special_tokens_ids"	,							[token_id_to_test_setters]       )
         self.assertListEqual(getattr(A_	,							"additional_special_tokens"       )	,							[token_to_test_setters]       )
         self.assertListEqual(getattr(A_	,							"additional_special_tokens_ids"       )	,							[token_id_to_test_setters]       )







from scipy.stats import spearmanr

import datasets


__lowerCamelCase	:					List[str]			  =					"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

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

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

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



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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       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 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       spearmanr(A_	,							A_       )
       if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
        return {"spearmanr": results[0]}
