

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 						__magic_name__      (							lowerCamelCase__		,	unittest.TestCase							):

   '''simple docstring'''




   lowerCamelCase__			:     str    =       PreTrainedTokenizerFast
   lowerCamelCase__			:     Union[str, Any]    =       False
   lowerCamelCase__			:     Tuple    =       True
   lowerCamelCase__			:     Any    =       'tokenizer_file'



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






     """simple docstring"""






     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:






     """simple docstring"""






     pass



   def 			_UpperCAmelCase			(    self	)							->   Dict:






     """simple docstring"""






     pass



   def 			_UpperCAmelCase			(    self	)							->   Dict:






     """simple docstring"""






     pass



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     pass



   def 			_UpperCAmelCase			(    self	)							->   Any:






     """simple docstring"""






     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	)							->   List[str]:






     """simple docstring"""






     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	)							->   Optional[Any]:






     """simple docstring"""






     a__  =self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name	)

     a__  =('''a''' for _ in range(1000	))
     a__  =tokenizer.train_new_from_iterator(text_iterator=lowercase_,   length=1000,   vocab_size=50	)

     a__  =new_tokenizer.encode('''a🤗'''	)
     self.assertEqual(lowercase_,   [64, 172, 253, 97, 245]	)







@require_tokenizers
class 						__magic_name__      (							unittest.TestCase							):

   '''simple docstring'''




   def 			_UpperCAmelCase			(    self	)							->   Tuple:






     """simple docstring"""






     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	)							->   Dict:






     """simple docstring"""






     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_	),   28997	)
     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_	),   28996	)
     a__  =json.loads(old_tokenizer._tokenizer.to_str()	)
     self.assertNotIn('''huggingface''',   json_tokenizer['''model''']['''vocab''']	)







@require_tokenizers
class 						__magic_name__      (							unittest.TestCase							):

   '''simple docstring'''




   def 			_UpperCAmelCase			(    self	)							->   Tuple:






     """simple docstring"""






     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,   lowercase_,   lowercase_	)							->   Union[str, Any]:






     """simple docstring"""






     return tokenizer.encode(lowercase_,   truncation='''longest_first''',   padding='''longest'''	)



import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata




def       UpperCAmelCase__    (      _A				:			str							):





  '''simple docstring'''







  a__  =min(re.search('''^ +'''     ,				_A							).end() if t.startswith(''' '''							) else 0 for t in string.splitlines()							)
  return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(_A							)]							)


lowerCamelCase									= '''\
---
language:
- zh
- en
task_ids:
- sentiment-classification
---
# Begin of markdown

Some cool dataset card
'''

lowerCamelCase									= '''\
---
---
# Begin of markdown

Some cool dataset card
'''


lowerCamelCase									= '''\
# Begin of markdown

Some cool dataset card
'''







class 						__magic_name__      (							unittest.TestCase							):

   '''simple docstring'''




   def 			_UpperCAmelCase			(    self	)							->   Optional[Any]:






     """simple docstring"""






     with tempfile.TemporaryDirectory() as tmp_dir:
       a__  =Path(lowercase_	) / '''README.md'''
       with open(lowercase_,   '''w+'''	) as readme_file:
         readme_file.write(lowercase_	)
       a__  =DatasetMetadata.from_readme(lowercase_	)
       self.assertDictEqual(lowercase_,   {'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}	)

       with open(lowercase_,   '''w+'''	) as readme_file:
         readme_file.write(lowercase_	)
       a__  =DatasetMetadata.from_readme(lowercase_	)
       self.assertDictEqual(lowercase_,   {}	)

       with open(lowercase_,   '''w+'''	) as readme_file:
         readme_file.write(lowercase_	)
       a__  =DatasetMetadata.from_readme(lowercase_	)
       self.assertEqual(lowercase_,   {}	)



   def 			_UpperCAmelCase			(    self	)							->   Optional[Any]:






     """simple docstring"""






     a__  =_dedent(
         '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            '''	)
     assert DatasetMetadata.from_yaml_string(lowercase_	)

     a__  =_dedent(
         '''\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            '''	)
     with self.assertRaises(lowercase_	):
       DatasetMetadata.from_yaml_string(lowercase_	)

     a__  =_dedent(
         '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            '''	)
     assert DatasetMetadata.from_yaml_string(lowercase_	)
