





import json
import os
import unittest
from typing import Tuple

from transformers import WavaVecaPhonemeCTCTokenizer
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput
from transformers.testing_utils import require_phonemizer

from ...test_tokenization_common import TokenizerTesterMixin


@require_phonemizer
class        __magic_name__	(				a_     ,					unittest.TestCase				):





     """simple docstring"""



     __UpperCamelCase            =  WavaVecaPhonemeCTCTokenizer
     __UpperCamelCase            =  False



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        super().setUp()

        A_       :					Tuple        =      (
            '''<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː '''
            '''ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː '''
            '''ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 '''
            '''oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ '''
            '''pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ '''
            '''yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ '''
            '''əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ '''
            '''ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ '''
            '''ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ '''
            '''uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ '''
            '''ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ '''
            '''ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ '''
            '''ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4'''
        ).split(" "	)
        A_       :					str        =      dict(zip(lowercase_      ,   range(len(lowercase_	)	)	)	)

        A_       :					Dict        =      {'''pad_token''': '''<pad>''', '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>'''}

        A_       :					Union[str, Any]        =      os.path.join(self.tmpdirname      ,   VOCAB_FILES_NAMES["vocab_file"]	)
        with open(self.vocab_file      ,   "w"      ,   encoding="utf-8"	) as fp:
           fp.write(json.dumps(lowercase_	) + "\n"	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]      ,   snake_case							:int      ,   snake_case							:List[str]=False      ,   snake_case							:Any=20      ,   snake_case							:int=5	):





        '''simple docstring'''




        A_       :					Union[str, Any]        =      [(i, tokenizer.decode([i]      ,   clean_up_tokenization_spaces=lowercase_	)) for i in range(len(lowercase_	)	)]
        A_       :					int        =      list(filter(lambda snake_case	: [t[0]] == tokenizer.encode(t[1]      ,   do_phonemize=lowercase_	)      ,   lowercase_	)	)
        if max_length is not None and len(lowercase_	) > max_length:
           A_       :					int        =      toks[:max_length]
        if min_length is not None and len(lowercase_	) < min_length and len(lowercase_	) > 0:
           while len(lowercase_	) < min_length:
              A_       :					List[str]        =      toks + toks
        # toks_str = [t[1] for t in toks]
        A_       :					List[Any]        =      [t[0] for t in toks]

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



     def     SCREAMING_SNAKE_CASE		(				self							:Any      ,   **snake_case							:Union[str, Any]	):





        '''simple docstring'''




        kwargs.update(self.special_tokens_map	)
        return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname      ,   **lowercase_	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        A_       :					int        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)

        # check adding a single token
        tokenizer.add_tokens("xxx"	)
        A_       :					Any        =      tokenizer("m xxx ɪ"      ,   do_phonemize=lowercase_	).input_ids
        self.assertEqual(lowercase_      ,   [13, 392, 17]	)  # xxx should be last token

        tokenizer.add_tokens(["aaa", "bbb", "ccc"]	)
        A_       :					Tuple        =      tokenizer("m aaa ɪ ccc"      ,   do_phonemize=lowercase_	).input_ids
        self.assertEqual(lowercase_      ,   [13, 393, 17, 395]	)  # aaa and ccc should be after xxx and 2 after aaa

        A_       :					List[Any]        =      tokenizer("maɪ c"      ,   do_phonemize=lowercase_	).input_ids
        self.assertEqual(lowercase_      ,   [3, 200]	)  # mai should be <unk> (=3)



     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        A_       :					Any        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)

        A_       :					int        =      '''Hello how are you'''
        A_       :					List[Any]        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)
        self.assertEqual(lowercase_      ,   "h ə l oʊ h aʊ ɑːɹ j uː"	)



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        A_       :					str        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)

        A_       :					List[Any]        =      '''Hello how are you'''
        A_       :					str        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)
        self.assertEqual(tokenizer(lowercase_	).input_ids      ,   tokenizer(lowercase_      ,   do_phonemize=lowercase_	).input_ids	)



     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        A_       :					str        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)
        A_       :					str        =      '''Hello how are you'''
        A_       :					Any        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)

        A_       :					List[Any]        =      tokenizer.decode(tokenizer(lowercase_	).input_ids	)

        self.assertEqual(lowercase_      ,   lowercase_	)



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        A_       :					Tuple        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)

        A_       :					int        =      [
            [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98],
            [24, 22, 5, 24, 22, 5, 77],
        ]
        A_       :					List[str]        =      tokenizer.decode(sample_ids[0]	)
        A_       :					List[str]        =      tokenizer.batch_decode(lowercase_	)
        self.assertEqual(lowercase_      ,   batch_tokens[0]	)
        self.assertEqual(lowercase_      ,   ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]	)



     def     SCREAMING_SNAKE_CASE		(				self							:str	):





        '''simple docstring'''




        A_       :					int        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        A_       :					Optional[Any]        =      '''Hello how are you'''
        A_       :					Union[str, Any]        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)
        self.assertEqual(lowercase_      ,   "h ə l oʊ | h aʊ | ɑːɹ | j uː |"	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        A_       :					List[str]        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        A_       :					Dict        =      '''Hello how are you'''
        A_       :					Union[str, Any]        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)
        self.assertEqual(tokenizer(lowercase_	).input_ids      ,   tokenizer(lowercase_      ,   do_phonemize=lowercase_	).input_ids	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        A_       :					Optional[int]        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        # fmt: off
        A_       :					Union[str, Any]        =      [
            [11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98],
            [tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77],
        ]
        # fmt: on

        # decode with word_del_token filter
        A_       :					Any        =      tokenizer.decode(sample_ids[0]	)
        A_       :					Optional[int]        =      tokenizer.batch_decode(lowercase_	)
        self.assertEqual(lowercase_      ,   batch_tokens[0]	)
        self.assertEqual(lowercase_      ,   ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]	)

        # decode with no word_del_token filter
        A_       :					Optional[Any]        =      tokenizer.decode(sample_ids[0]      ,   filter_word_delimiter_token=lowercase_	)
        A_       :					Any        =      tokenizer.batch_decode(lowercase_      ,   filter_word_delimiter_token=lowercase_	)
        self.assertEqual(lowercase_      ,   batch_tokens[0]	)
        self.assertEqual(lowercase_      ,   ["k s ɾ | ɾ l | ɭʲ", "| j ð | s j ð s oːɹ"]	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					List[Any]        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        A_       :					Optional[int]        =      '''Hello how are you'''
        A_       :					Dict        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)

        A_       :					Tuple        =      tokenizer.decode(tokenizer(lowercase_	).input_ids      ,   filter_word_delimiter_token=lowercase_	)

        self.assertEqual(lowercase_      ,   lowercase_	)



     def     SCREAMING_SNAKE_CASE		(				self							:Union[str, Any]	):





        '''simple docstring'''




        A_       :					str        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        A_       :					Optional[int]        =      '''Hello how are you'''
        A_       :					List[Any]        =      tokenizer.phonemize(lowercase_      ,   phonemizer_lang="en-us"	)

        A_       :					int        =      tokenizer.decode(tokenizer(lowercase_	).input_ids      ,   filter_word_delimiter_token=lowercase_	)

        self.assertEqual(" ".join([p.strip() for p in phonemes.split(" |"	)]	).strip()      ,   lowercase_	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					int        =      self.tokenizer_class.from_pretrained(
            "facebook/wav2vec2-lv-60-espeak-cv-ft"      ,   word_delimiter_token=lowercase_	)
        A_       :					int        =      '''Hello how are you'''

        A_       :					Union[str, Any]        =      tokenizer(lowercase_      ,   phonemizer_lang="en-us"	).input_ids
        A_       :					List[Any]        =      tokenizer(lowercase_      ,   phonemizer_lang="fr-fr"	).input_ids

        self.assertNotEqual(lowercase_      ,   lowercase_	)

        A_       :					str        =      tokenizer.decode(lowercase_	)
        A_       :					Optional[Any]        =      tokenizer.decode(lowercase_	)

        self.assertEqual(lowercase_      ,   "h ə l oʊ h aʊ ɑːɹ j uː"	)
        self.assertEqual(lowercase_      ,   "ɛ l o h aʊ a ʁ j u"	)



     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        A_       :					Dict        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)
        A_       :					List[str]        =      '''Hello how Are you'''
        A_       :					Union[str, Any]        =      '''hello how are you'''

        A_       :					List[Any]        =      tokenizer(lowercase_	).input_ids
        A_       :					List[str]        =      tokenizer(lowercase_	).input_ids

        self.assertEqual(lowercase_      ,   lowercase_	)



     def     SCREAMING_SNAKE_CASE		(				self							:Union[str, Any]	):





        '''simple docstring'''




        A_       :					Any        =      self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft"	)
        tokenizer.add_tokens(["!", "?"]	)
        tokenizer.add_special_tokens({"cls_token": "$$$"}	)

        # fmt: off
        A_       :					Dict        =      [
            [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 392, 392, 393, 392, 392, 393, 394, 394],
            [24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 394, 394],
        ]
        # fmt: on

        A_       :					Tuple        =      tokenizer.batch_decode(lowercase_	)
        self.assertEqual(lowercase_      ,   ["k s ɾ ɾ l ɭʲ!?!? $$$", "j ð s j ð s oːɹ $$$"]	)



     @staticmethod
     def     SCREAMING_SNAKE_CASE		(				snake_case							:Optional[int]      ,   snake_case							:Union[str, Any]	):





        '''simple docstring'''




        A_       :					Union[str, Any]        =      [d[key] for d in offsets]
        return retrieved_list



     def     SCREAMING_SNAKE_CASE		(				self							:str	):





        '''simple docstring'''




        A_       :					List[str]        =      self.get_tokenizer(word_delimiter_token="|"	)
        tokenizer.add_tokens("|"	)

        # fmt: off
        # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ"
        A_       :					Optional[int]        =      [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98]
        # fmt: on

        A_       :					Union[str, Any]        =      tokenizer.decode(lowercase_      ,   output_char_offsets=lowercase_      ,   filter_word_delimiter_token=lowercase_	)
        # check Wav2Vec2CTCTokenizerOutput keys for char
        self.assertEqual(len(outputs.keys()	)      ,   2	)
        self.assertTrue("text" in outputs	)
        self.assertTrue("char_offsets" in outputs	)
        self.assertTrue(isinstance(lowercase_      ,   lowercase_	)	)

        # check that order of chars is correct and identical for both outputs
        self.assertEqual(" ".join(self.get_from_offsets(outputs["char_offsets"]      ,   "char"	)	)      ,   outputs.text	)
        self.assertListEqual(
            self.get_from_offsets(outputs["char_offsets"]      ,   "char"	)      ,   ["k", "s", "ɾ", "ɾ", "|", "ɾ", "l", "|", "ɭʲ"]	)

        # check that offsets are actually correct for char
        # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token,
        # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98
        self.assertListEqual(
            self.get_from_offsets(outputs["char_offsets"]      ,   "start_offset"	)      ,   [0, 1, 4, 7, 9, 11, 12, 15, 16]	)
        self.assertListEqual(
            self.get_from_offsets(outputs["char_offsets"]      ,   "end_offset"	)      ,   [1, 4, 6, 9, 10, 12, 15, 16, 17]	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					List[str]        =      self.get_tokenizer(word_delimiter_token="|"	)

        def check_list_tuples_equal(snake_case							:str      ,   snake_case							:Any	):
           self.assertTrue(isinstance(lowercase_      ,   lowercase_	)	)
           self.assertTrue(isinstance(outputs_list[0]      ,   lowercase_	)	)

           # transform list to ModelOutput
           A_       :					int        =      WavaVecaPhonemeCTCTokenizerOutput(
               {k: [d[k] for d in outputs_list] for k in outputs_list[0]}	)

           self.assertListEqual(outputs_batch["text"]      ,   outputs_batch_a["text"]	)

           def recursive_check(snake_case							:int      ,   snake_case							:str	):
              if isinstance(lowercase_      ,   lowercase_	):
                 [recursive_check(lowercase_      ,   lowercase_	) for la, la in zip(lowercase_      ,   lowercase_	)]
              self.assertEqual(lowercase_      ,   lowercase_	)

           if "char_offsets" in outputs_batch:
              recursive_check(outputs_batch["char_offsets"]      ,   outputs_batch_a["char_offsets"]	)

        # fmt: off
        A_       :					int        =      [
            [11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34],
            [24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34],
        ]
        # fmt: on

        # We assume that `decode` works as expected. All we will check now is
        # the output type is correct and the output is identical to `decode`

        # char
        A_       :					int        =      tokenizer.batch_decode(lowercase_      ,   output_char_offsets=lowercase_	)
        A_       :					Optional[Any]        =      [tokenizer.decode(lowercase_      ,   output_char_offsets=lowercase_	) for ids in sample_ids]
        check_list_tuples_equal(lowercase_      ,   lowercase_	)



     @unittest.skip("Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes"	)
     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        pass



     @unittest.skip("Wav2Vec2PhonemeTokenizer always puts spaces between phonemes"	)
     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        pass



     @unittest.skip("encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency"	)
     def     SCREAMING_SNAKE_CASE		(				self							:Dict	):





        '''simple docstring'''




        pass



     @unittest.skip("Wav2Vec2PhonemeModel has no max model length => no testing"	)
     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        pass



     def     SCREAMING_SNAKE_CASE		(				self							:Union[str, Any]	):





        '''simple docstring'''




        A_       :					List[Any]        =      self.get_tokenizers(do_lower_case=lowercase_	)
        for tokenizer in tokenizers:
           with self.subTest(f"{tokenizer.__class__.__name__}"	):
              A_       :					str        =      tokenizer.vocab_size
              A_       :					List[str]        =      len(lowercase_	)

              self.assertNotEqual(lowercase_      ,   0	)

              # We usually have added tokens from the start in tests because our vocab fixtures are
              # smaller than the original vocabs - let's not assert this
              # self.assertEqual(vocab_size, all_size)

              A_       :					Union[str, Any]        =      ['''aaaaa bbbbbb''', '''cccccccccdddddddd''']
              A_       :					Optional[int]        =      tokenizer.add_tokens(lowercase_	)
              A_       :					Optional[Any]        =      tokenizer.vocab_size
              A_       :					Optional[Any]        =      len(lowercase_	)

              self.assertNotEqual(lowercase_      ,   0	)
              self.assertEqual(lowercase_      ,   lowercase_	)
              self.assertEqual(lowercase_      ,   len(lowercase_	)	)
              self.assertEqual(lowercase_      ,   all_size + len(lowercase_	)	)

              A_       :					Tuple        =      tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l"      ,   add_special_tokens=lowercase_	)

              self.assertGreaterEqual(len(lowercase_	)      ,   4	)
              self.assertGreater(tokens[0]      ,   tokenizer.vocab_size - 1	)
              self.assertGreater(tokens[-3]      ,   tokenizer.vocab_size - 1	)

              A_       :					Dict        =      {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''}
              A_       :					Any        =      tokenizer.add_special_tokens(lowercase_	)
              A_       :					Union[str, Any]        =      tokenizer.vocab_size
              A_       :					Tuple        =      len(lowercase_	)

              self.assertNotEqual(lowercase_      ,   0	)
              self.assertEqual(lowercase_      ,   lowercase_	)
              self.assertEqual(lowercase_      ,   len(lowercase_	)	)
              self.assertEqual(lowercase_      ,   all_size_a + len(lowercase_	)	)

              A_       :					List[Any]        =      tokenizer.encode(
                  ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l"      ,   add_special_tokens=lowercase_	)

              self.assertGreaterEqual(len(lowercase_	)      ,   6	)
              self.assertGreater(tokens[0]      ,   tokenizer.vocab_size - 1	)
              self.assertGreater(tokens[0]      ,   tokens[1]	)
              self.assertGreater(tokens[-3]      ,   tokenizer.vocab_size - 1	)
              self.assertGreater(tokens[-3]      ,   tokens[-4]	)
              self.assertEqual(tokens[0]      ,   tokenizer.eos_token_id	)
              self.assertEqual(tokens[-3]      ,   tokenizer.pad_token_id	)



     @unittest.skip("The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode."	)
     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        pass



     @unittest.skip("The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode."	)
     def     SCREAMING_SNAKE_CASE		(				self							:Tuple	):





        '''simple docstring'''




        pass





     def     SCREAMING_SNAKE_CASE		(				self							:Dict	):





        '''simple docstring'''




        A_       :					Any        =      self.get_tokenizers(fast=lowercase_      ,   do_lower_case=lowercase_	)
        for tokenizer in tokenizers:
           with self.subTest(f"{tokenizer.__class__.__name__}"	):
              A_       :					Tuple        =      ['''ð''', '''ɪ''', '''s''', '''ɪ''', '''z''', '''ɐ''', '''t''', '''ɛ''', '''k''', '''s''', '''t''']
              A_       :					Optional[Any]        =      tokenizer.convert_tokens_to_string(lowercase_	)

              self.assertIsInstance(output["text"]      ,   lowercase_	)



"""simple docstring"""





import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
							import jax.numpy as jnp







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def __get__(			self     :							List[Any]  ,lowercase_     :							Any  ,lowercase_     :							List[str]=None						):
						# See docs.python.org/3/howto/descriptor.html#properties
						if obj is None:
							return self
						if self.fget is None:
							raise AttributeError('''unreadable attribute'''						)
						lowerCAmelCase__      :		Optional[Any]    							=      '''__cached_''' + self.fget.__name__
						lowerCAmelCase__      :		Any    							=      getattr(lowercase_  ,lowercase_  ,lowercase_						)
						if cached is None:
							lowerCAmelCase__      :		str    							=      self.fget(lowercase_						)
							setattr(lowercase_  ,lowercase_  ,lowercase_						)
						return cached

def     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		int    							=      val.lower()
	if val in {"y", "yes", "t", "true", "on", "1"}:
		return 1
	if val in {"n", "no", "f", "false", "off", "0"}:
		return 0
	raise ValueError(f'invalid truth value {val!r}'					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if is_torch_fx_proxy(A_					):
		return True
	if is_torch_available():
		import torch

		if isinstance(A_		,	torch.Tensor					):
			return True
	if is_tf_available():
		import tensorflow as tf

		if isinstance(A_		,	tf.Tensor					):
			return True

	if is_flax_available():
		import jax.numpy as jnp
		from jax.core import Tracer

		if isinstance(A_		,	(jnp.ndarray, Tracer)					):
			return True

	return isinstance(A_		,	np.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return isinstance(A_		,	np.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return _is_numpy(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	return isinstance(A_		,	torch.Tensor					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	return isinstance(A_		,	torch.device					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch_device(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	if isinstance(A_		,	A_					):
		if hasattr(A_		,	A_					):
			lowerCAmelCase__      :		int    							=      getattr(A_		,	A_					)
		else:
			return False
	return isinstance(A_		,	torch.dtype					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch_dtype(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import tensorflow as tf

	return isinstance(A_		,	tf.Tensor					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_tf_available() else _is_tensorflow(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import tensorflow as tf

	# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
	if hasattr(A_		,	'''is_symbolic_tensor'''					):
		return tf.is_symbolic_tensor(A_					)
	return type(A_					) == tf.Tensor

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_tf_available() else _is_tf_symbolic_tensor(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import jax.numpy as jnp  # noqa: F811

	return isinstance(A_		,	jnp.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_flax_available() else _is_jax(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if isinstance(A_		,	(dict, UserDict)					):
		return {k: to_py_obj(A_					) for k, v in obj.items()}
	elif isinstance(A_		,	(list, tuple)					):
		return [to_py_obj(A_					) for o in obj]
	elif is_tf_tensor(A_					):
		return obj.numpy().tolist()
	elif is_torch_tensor(A_					):
		return obj.detach().cpu().tolist()
	elif is_jax_tensor(A_					):
		return np.asarray(A_					).tolist()
	elif isinstance(A_		,	(np.ndarray, np.number)					):  # tolist also works on 0d np arrays
		return obj.tolist()
	else:
		return obj

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if isinstance(A_		,	(dict, UserDict)					):
		return {k: to_numpy(A_					) for k, v in obj.items()}
	elif isinstance(A_		,	(list, tuple)					):
		return np.array(A_					)
	elif is_tf_tensor(A_					):
		return obj.numpy()
	elif is_torch_tensor(A_					):
		return obj.detach().cpu().numpy()
	elif is_jax_tensor(A_					):
		return np.asarray(A_					)
	else:
		return obj







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							Any						):
						lowerCAmelCase__      :		Optional[int]    							=      fields(self						)

						# Safety and consistency checks
						if not len(lowercase_						):
							raise ValueError(F'{self.__class__.__name__} has no fields.'						)
						if not all(field.default is None for field in class_fields[1:]						):
							raise ValueError(F'{self.__class__.__name__} should not have more than one required field.'						)

						lowerCAmelCase__      :		str    							=      getattr(self  ,class_fields[0].name						)
						lowerCAmelCase__      :		List[str]    							=      all(getattr(self  ,field.name						) is None for field in class_fields[1:]						)

						if other_fields_are_none and not is_tensor(lowercase_						):
							if isinstance(lowercase_  ,lowercase_						):
								lowerCAmelCase__      :		str    							=      first_field.items()
								lowerCAmelCase__      :		List[str]    							=      True
							else:
								try:
									lowerCAmelCase__      :		Union[str, Any]    							=      iter(lowercase_						)
									lowerCAmelCase__      :		int    							=      True
								except TypeError:
									lowerCAmelCase__      :		Dict    							=      False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
							if first_field_iterator:
								for idx, element in enumerate(lowercase_						):
									if (
									    not isinstance(lowercase_  ,(list, tuple)						)
									    or not len(lowercase_						) == 2
									    or not isinstance(element[0]  ,lowercase_						)
									):
										if idx == 0:
											# If we do not have an iterator of key/values, set it as attribute
											lowerCAmelCase__      :		Tuple    							=      first_field
										else:
											# If we have a mixed iterator, raise an error
											raise ValueError(
											    F'Cannot set key/value for {element}. It needs to be a tuple (key, value).'						)
										break
									setattr(self  ,element[0]  ,element[1]						)
									if element[1] is not None:
										lowerCAmelCase__      :		Dict    							=      element[1]
							elif first_field is not None:
								lowerCAmelCase__      :		Any    							=      first_field
						else:
							for field in class_fields:
								lowerCAmelCase__      :		Any    							=      getattr(self  ,field.name						)
								if v is not None:
									lowerCAmelCase__      :		List[str]    							=      v







					def __delitem__(			self     :							List[str]  ,*lowercase_     :							List[str]  ,**lowercase_     :							Any						):
						raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]  ,*lowercase_     :							Union[str, Any]  ,**lowercase_     :							List[Any]						):
						raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'						)







					def 			__lowerCAmelCase					(			self     :							str  ,*lowercase_     :							Union[str, Any]  ,**lowercase_     :							Any						):
						raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.'						)







					def 			__lowerCAmelCase					(			self     :							int  ,*lowercase_     :							List[str]  ,**lowercase_     :							int						):
						raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.'						)







					def __getitem__(			self     :							Any  ,lowercase_     :							Any						):
						if isinstance(lowercase_  ,lowercase_						):
							lowerCAmelCase__      :		Optional[Any]    							=      dict(self.items()						)
							return inner_dict[k]
						else:
							return self.to_tuple()[k]







					def __setattr__(			self     :							Dict  ,lowercase_     :							Dict  ,lowercase_     :							int						):
						if name in self.keys() and value is not None:
							# Don't call self.__setitem__ to avoid recursion errors
							super().__setitem__(lowercase_  ,lowercase_						)
						super().__setattr__(lowercase_  ,lowercase_						)







					def __setitem__(			self     :							str  ,lowercase_     :							Optional[int]  ,lowercase_     :							Optional[Any]						):
						# Will raise a KeyException if needed
						super().__setitem__(lowercase_  ,lowercase_						)
						# Don't call self.__setattr__ to avoid recursion errors
						super().__setattr__(lowercase_  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						return tuple(self[k] for k in self.keys()						)







class 							SCREAMING_SNAKE_CASE   (						a_       ,				a_			):






					"""simple docstring"""



					@classmethod
					def 			__lowerCAmelCase					(			cls     :							Dict  ,lowercase_     :							Optional[Any]						):
						raise ValueError(
						    F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()						)}'						)







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			"longest"
					lowercase__												=			"max_length"
					lowercase__												=			"do_not_pad"







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			"pt"
					lowercase__												=			"tf"
					lowercase__												=			"np"
					lowercase__												=			"jax"







class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							List[Any]  ,lowercase_     :							List[ContextManager]						):
						lowerCAmelCase__      :		Optional[int]    							=      context_managers
						lowerCAmelCase__      :		Tuple    							=      ExitStack()







					def __enter__(			self     :							str						):
						for context_manager in self.context_managers:
							self.stack.enter_context(lowercase_						)







					def __exit__(			self     :							Tuple  ,*lowercase_     :							Tuple  ,**lowercase_     :							List[Any]						):
						self.stack.__exit__(*lowercase_  ,**lowercase_						)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		Union[str, Any]    							=      infer_framework(A_					)
	if framework == "tf":
		lowerCAmelCase__      :		List[str]    							=      inspect.signature(model_class.call					)  # TensorFlow models
	elif framework == "pt":
		lowerCAmelCase__      :		Any    							=      inspect.signature(model_class.forward					)  # PyTorch models
	else:
		lowerCAmelCase__      :		Dict    							=      inspect.signature(model_class.__call__					)  # Flax models

	for p in signature.parameters:
		if p == "return_loss" and signature.parameters[p].default is True:
			return True

	return False

def     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		List[str]    							=      model_class.__name__
	lowerCAmelCase__      :		List[Any]    							=      infer_framework(A_					)
	if framework == "tf":
		lowerCAmelCase__      :		Tuple    							=      inspect.signature(model_class.call					)  # TensorFlow models
	elif framework == "pt":
		lowerCAmelCase__      :		List[str]    							=      inspect.signature(model_class.forward					)  # PyTorch models
	else:
		lowerCAmelCase__      :		Optional[int]    							=      inspect.signature(model_class.__call__					)  # Flax models

	if "QuestionAnswering" in model_name:
		return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
	else:
		return [p for p in signature.parameters if "label" in p]

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_ = ""		,	A_ = "."					):

	def _flatten_dict(A_		,	A_=""		,	A_="."					):
		for k, v in d.items():
			lowerCAmelCase__      :		Any    							=      str(A_					) + delimiter + str(A_					) if parent_key else k
			if v and isinstance(A_		,	A_					):
				yield from flatten_dict(A_		,	A_		,	delimiter=A_					).items()
			else:
				yield key, v

	return dict(_flatten_dict(A_		,	A_		,	A_					)					)

@contextmanager
def     __SCREAMING_SNAKE_CASE    ( A_		,	A_ = False					):
	if use_temp_dir:
		with tempfile.TemporaryDirectory() as tmp_dir:
			yield tmp_dir
	else:
		yield working_dir

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_=None					):
	if is_numpy_array(A_					):
		return np.transpose(A_		,	axes=A_					)
	elif is_torch_tensor(A_					):
		return array.T if axes is None else array.permute(*A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

		return tf.transpose(A_		,	perm=A_					)
	elif is_jax_tensor(A_					):
		return jnp.transpose(A_		,	axes=A_					)
	else:
		raise ValueError(f'Type not supported for transpose: {type(A_					)}.'					)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	if is_numpy_array(A_					):
		return np.reshape(A_		,	A_					)
	elif is_torch_tensor(A_					):
		return array.reshape(*A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

		return tf.reshape(A_		,	A_					)
	elif is_jax_tensor(A_					):
		return jnp.reshape(A_		,	A_					)
	else:
		raise ValueError(f'Type not supported for reshape: {type(A_					)}.'					)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_=None					):
	if is_numpy_array(A_					):
		return np.squeeze(A_		,	axis=A_					)
	elif is_torch_tensor(A_					):
		return array.squeeze() if axis is None else array.squeeze(dim=A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

		return tf.squeeze(A_		,	axis=A_					)
	elif is_jax_tensor(A_					):
		return jnp.squeeze(A_		,	axis=A_					)
	else:
		raise ValueError(f'Type not supported for squeeze: {type(A_					)}.'					)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	if is_numpy_array(A_					):
		return np.expand_dims(A_		,	A_					)
	elif is_torch_tensor(A_					):
		return array.unsqueeze(dim=A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

		return tf.expand_dims(A_		,	axis=A_					)
	elif is_jax_tensor(A_					):
		return jnp.expand_dims(A_		,	axis=A_					)
	else:
		raise ValueError(f'Type not supported for expand_dims: {type(A_					)}.'					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if is_numpy_array(A_					):
		return np.size(A_					)
	elif is_torch_tensor(A_					):
		return array.numel()
	elif is_tf_tensor(A_					):
		import tensorflow as tf

		return tf.size(A_					)
	elif is_jax_tensor(A_					):
		return array.size
	else:
		raise ValueError(f'Type not supported for expand_dims: {type(A_					)}.'					)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	for key, value in auto_map.items():
		if isinstance(A_		,	(tuple, list)					):
			lowerCAmelCase__      :		Tuple    							=      [f'{repo_id}--{v}' if (v is not None and '''--''' not in v) else v for v in value]
		elif value is not None and "--" not in value:
			lowerCAmelCase__      :		Tuple    							=      f'{repo_id}--{value}'

	return auto_map





def     __SCREAMING_SNAKE_CASE    ( A_					):
	for base_class in inspect.getmro(A_					):
		lowerCAmelCase__      :		List[str]    							=      base_class.__module__
		lowerCAmelCase__      :		List[Any]    							=      base_class.__name__
		if module.startswith('''tensorflow'''					) or module.startswith('''keras'''					) or name == "TFPreTrainedModel":
			return "tf"
		elif module.startswith('''torch'''					) or name == "PreTrainedModel":
			return "pt"
		elif module.startswith('''flax'''					) or module.startswith('''jax'''					) or name == "FlaxPreTrainedModel":
			return "flax"
	else:
		raise TypeError(f'Could not infer framework from class {model_class}.'					)




