





'''simple docstring'''

import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class      UpperCAmelCase			( UpperCamelCase__    , unittest.TestCase       ):
 __lowercase     	=       PreTrainedTokenizerFast
 __lowercase     	=       False
 __lowercase     	=       True
 __lowercase     	=       """tokenizer_file"""
 def   UpperCAmelCase_							(       self   :Dict							)->							Optional[int]:
     A__       =    False  # because we don't have pretrained_vocab_files_map
     super().setUp()
     A__       =    True

     A__       =    ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"]
     A__       =    "SaulLu/dummy-tokenizer-bytelevel-bpe"

     # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
     A__       =    [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

     A__       =    PreTrainedTokenizerFast.from_pretrained(model_paths[0]							)
     tokenizer.save_pretrained(self.tmpdirname							)
 def   UpperCAmelCase_							(       self   :Dict							)->							List[Any]:
     # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
     # model
     pass
 def   UpperCAmelCase_							(       self   :Dict							)->							Tuple:
     # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
     # model
     pass
 def   UpperCAmelCase_							(       self   :Union[str, Any]							)->							Dict:
     # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
     # model
     pass
 def   UpperCAmelCase_							(       self   :Any							)->							Any:
     # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
     pass
 def   UpperCAmelCase_							(       self   :int							)->							Dict:
     A__       =    self.tmpdirname
     # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"							):
             try:
                 A__       =    tempfile.mkdtemp()
                 A__       =    self.rust_tokenizer_class.from_pretrained(lowercase_		, **lowercase_							)

                 tokenizer.save_pretrained(self.tmpdirname							)
                 super().test_training_new_tokenizer()
             finally:
                 # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                 # is restored
                 shutil.rmtree(self.tmpdirname							)
                 A__       =    tmpdirname_orig
 def   UpperCAmelCase_							(       self   :Dict							)->							Tuple:
     A__       =    self.tmpdirname
     # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"							):
             try:
                 A__       =    tempfile.mkdtemp()
                 A__       =    self.rust_tokenizer_class.from_pretrained(lowercase_		, **lowercase_							)

                 tokenizer.save_pretrained(self.tmpdirname							)
                 super().test_training_new_tokenizer_with_special_tokens_change()
             finally:
                 # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                 # is restored
                 shutil.rmtree(self.tmpdirname							)
                 A__       =    tmpdirname_orig



 def   UpperCAmelCase_							(       self   :str							)->							Union[str, Any]:
     A__       =    self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name							)

     A__       =    ("a" for _ in range(10_00							))
     A__       =    tokenizer.train_new_from_iterator(text_iterator=lowercase_		, length=10_00		, vocab_size=50							)

     A__       =    new_tokenizer.encode("a🤗"							)
     self.assertEqual(lowercase_		, [64, 1_72, 2_53, 97, 2_45]							)






@require_tokenizers
class      UpperCAmelCase			( unittest.TestCase       ):
 def   UpperCAmelCase_							(       self   :List[Any]							)->							List[str]:
     A__       =    AutoTokenizer.from_pretrained("bert-base-cased"							)
     A__       =    json.loads(tokenizer._tokenizer.to_str()							)
     A__       =    len(lowercase_							)

     with tempfile.TemporaryDirectory() as tmp_dir:
         # Hack to save this in the tokenizer_config.json
         A__       =    ["tokenizer.4.0.0.json"]
         tokenizer.save_pretrained(lowercase_							)
         json.dump(lowercase_		, open(os.path.join(lowercase_		, "tokenizer.4.0.0.json"							)		, "w"							)							)

         # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
         A__       =    AutoTokenizer.from_pretrained(lowercase_							)
         self.assertEqual(len(lowercase_							)		, len(lowercase_							) + 1							)
         A__       =    json.loads(new_tokenizer._tokenizer.to_str()							)
         self.assertIn("huggingface"		, json_tokenizer["model"]["vocab"]							)

         # Will need to be adjusted if we reach v42 and this test is still here.
         # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
         shutil.move(os.path.join(lowercase_		, "tokenizer.4.0.0.json"							)		, os.path.join(lowercase_		, "tokenizer.42.0.0.json"							)							)
         A__       =    ["tokenizer.42.0.0.json"]
         tokenizer.save_pretrained(lowercase_							)
         A__       =    AutoTokenizer.from_pretrained(lowercase_							)
         self.assertEqual(len(lowercase_							)		, len(lowercase_							)							)
         A__       =    json.loads(new_tokenizer._tokenizer.to_str()							)
         self.assertNotIn("huggingface"		, json_tokenizer["model"]["vocab"]							)



 def   UpperCAmelCase_							(       self   :int							)->							List[Any]:
     # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
     A__       =    "hf-internal-testing/test-two-tokenizers"

     # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
     A__       =    AutoTokenizer.from_pretrained(lowercase_							)
     self.assertEqual(len(lowercase_							)		, 2_89_97							)
     A__       =    json.loads(tokenizer._tokenizer.to_str()							)
     self.assertIn("huggingface"		, json_tokenizer["model"]["vocab"]							)

     # Testing an older version by monkey-patching the version in the module it's used.
     import transformers as old_transformers

     A__       =    "3.0.0"
     A__       =    old_transformers.models.auto.AutoTokenizer.from_pretrained(lowercase_							)
     self.assertEqual(len(lowercase_							)		, 2_89_96							)
     A__       =    json.loads(old_tokenizer._tokenizer.to_str()							)
     self.assertNotIn("huggingface"		, json_tokenizer["model"]["vocab"]							)






@require_tokenizers
class      UpperCAmelCase			( unittest.TestCase       ):
 def   UpperCAmelCase_							(       self   :Union[str, Any]							)->							str:
     # See https://github.com/huggingface/transformers/pull/12550
     # and https://github.com/huggingface/tokenizers/issues/537
     A__       =    PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel"							)
     A__       =    "The Matrix is a 1999 science fiction action film."

     with concurrent.futures.ThreadPoolExecutor() as executor:
         A__       =    [executor.submit(self.fetch		, lowercase_		, lowercase_							) for i in range(10							)]
         A__       =    [future.result() for future in futures]
         self.assertEqual(lowercase_		, [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10							)]							)



 def   UpperCAmelCase_							(       self   :Optional[Any]		, lowercase_   :str		, lowercase_   :Union[str, Any]							)->							Tuple:
     return tokenizer.encode(lowercase_		, truncation="longest_first"		, padding="longest"							)










'''simple docstring'''

import os
import tempfile
import unittest
from typing import List

from transformers.models.esm.tokenization_esm import VOCAB_FILES_NAMES, EsmTokenizer
from transformers.testing_utils import require_tokenizers
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.tokenization_utils_base import PreTrainedTokenizerBase






@require_tokenizers
class      UpperCAmelCase			( unittest.TestCase       ):
 __lowercase     	=       EsmTokenizer
 def   UpperCAmelCase_							(       self   :Any							)->							int:
     super().setUp()
     A__       =    tempfile.mkdtemp()
     # fmt: off
     A__       =    ["<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>"]  # noqa: E501
     # fmt: on
     A__       =    os.path.join(self.tmpdirname		, VOCAB_FILES_NAMES["vocab_file"]							)
     with open(self.vocab_file		, "w"		, encoding="utf-8"							) as vocab_writer:
         vocab_writer.write("".join([x + "\n" for x in vocab_tokens]							)							)
 def   UpperCAmelCase_							(       self   :Any		, **lowercase_   :int							)->							List[PreTrainedTokenizerBase]:
     return [self.get_tokenizer(**lowercase_							)]
 def   UpperCAmelCase_							(       self   :Any		, **lowercase_   :Dict							)->							PreTrainedTokenizer:
     return self.tokenizer_class.from_pretrained(self.tmpdirname		, **lowercase_							)
 def   UpperCAmelCase_							(       self   :int							)->							Dict:
     A__       =    self.tokenizer_class(self.vocab_file							)

     A__       =    tokenizer.tokenize("LAGVS"							)
     self.assertListEqual(lowercase_		, ["L", "A", "G", "V", "S"]							)
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_							)		, [4, 5, 6, 7, 8]							)
 def   UpperCAmelCase_							(       self   :Tuple							)->							Tuple:
     A__       =    self.tokenizer_class(self.vocab_file							)

     A__       =    "LAGVS"
     self.assertListEqual(tokenizer.encode(lowercase_							)		, [0, 4, 5, 6, 7, 8, 2]							)
 def   UpperCAmelCase_							(       self   :Any							)->							Tuple:
     A__       =    self.tokenizer_class(self.vocab_file							)

     A__       =    ["LAGVS", "WCB"]
     A__       =    tokenizer(lowercase_		, padding=lowercase_							)["input_ids"]

     self.assertListEqual(lowercase_		, [[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2]]							)
 def   UpperCAmelCase_							(       self   :str							)->							Any:
     A__       =    self.tokenizer_class(self.vocab_file							)

     A__       =    ["LAGVS", "WCB"]
     A__       =    tokenizer(lowercase_		, padding=lowercase_							)["input_ids"]

     self.assertListEqual(lowercase_		, [[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2, 1, 1]]							)



 def   UpperCAmelCase_							(       self   :Optional[Any]							)->							List[str]:
     A__       =    self.get_tokenizers(fast=lowercase_							)
     for tokenizer in tokenizers:
         with self.subTest(F"{tokenizer.__class__.__name__}"							):
             A__       =    "<unk>"
             A__       =    "<mask>"

             A__       =    tokenizer.tokenize(lowercase_							)
             A__       =    tokenizer.tokenize(lowercase_							)

             self.assertEqual(len(lowercase_							)		, 1							)
             self.assertEqual(len(lowercase_							)		, 1							)
             self.assertEqual(token_a[0]		, lowercase_							)
             self.assertEqual(token_a[0]		, lowercase_							)



