




'''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 	SCREAMING_SNAKE_CASE(    __A       ,				unittest.TestCase					):
       snake_case_			:					Any   = PreTrainedTokenizerFast
       snake_case_			:					Optional[int]   = False
       snake_case_			:					Dict   = True
       snake_case_			:					Optional[int]   = """tokenizer_file"""

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

           """simple docstring"""



           __lowercase          =						False  # because we don't have pretrained_vocab_files_map
           super().setUp()
           __lowercase          =						True

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

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

           __lowercase          =						PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
           tokenizer.save_pretrained(self.tmpdirname					)

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Optional[int]:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						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:
                       __lowercase          =						tempfile.mkdtemp()
                       __lowercase          =						self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ ,		**lowerCamelCase__					)

                       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					)
                       __lowercase          =						tmpdirname_orig

       def    snake_case__      (   self					)   -> Optional[int]:

           """simple docstring"""



           __lowercase          =						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:
                       __lowercase          =						tempfile.mkdtemp()
                       __lowercase          =						self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ ,		**lowerCamelCase__					)

                       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					)
                       __lowercase          =						tmpdirname_orig




       def    snake_case__      (   self					)   -> Optional[int]:

           """simple docstring"""



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

           __lowercase          =						("""a""" for _ in range(1000					))
           __lowercase          =						tokenizer.train_new_from_iterator(text_iterator=lowerCamelCase__ ,		length=1000 ,		vocab_size=50					)

           __lowercase          =						new_tokenizer.encode("""a🤗"""					)
           self.assertEqual(lowerCamelCase__ ,		[64, 172, 253, 97, 245]					)






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						AutoTokenizer.from_pretrained("""bert-base-cased"""					)
           __lowercase          =						json.loads(tokenizer._tokenizer.to_str()					)
           __lowercase          =						len(lowerCamelCase__					)

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

               # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
               __lowercase          =						AutoTokenizer.from_pretrained(lowerCamelCase__					)
               self.assertEqual(len(lowerCamelCase__					) ,		len(lowerCamelCase__					) + 1					)
               __lowercase          =						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(lowerCamelCase__ ,		"""tokenizer.4.0.0.json"""					) ,		os.path.join(lowerCamelCase__ ,		"""tokenizer.42.0.0.json"""					)					)
               __lowercase          =						["""tokenizer.42.0.0.json"""]
               tokenizer.save_pretrained(lowerCamelCase__					)
               __lowercase          =						AutoTokenizer.from_pretrained(lowerCamelCase__					)
               self.assertEqual(len(lowerCamelCase__					) ,		len(lowerCamelCase__					)					)
               __lowercase          =						json.loads(new_tokenizer._tokenizer.to_str()					)
               self.assertNotIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)




       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						"""hf-internal-testing/test-two-tokenizers"""

           # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
           __lowercase          =						AutoTokenizer.from_pretrained(lowerCamelCase__					)
           self.assertEqual(len(lowerCamelCase__					) ,		2_8997					)
           __lowercase          =						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

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






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

       def    snake_case__      (   self					)   -> Optional[int]:

           """simple docstring"""



           __lowercase          =						PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""					)
           __lowercase          =						"""The Matrix is a 1999 science fiction action film."""

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




       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__					)   -> str:

           """simple docstring"""



           return tokenizer.encode(lowerCamelCase__ ,		truncation="""longest_first""" ,		padding="""longest"""					)










'''simple docstring'''
from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


A							:				Dict			     =	{
    """id""": """5733be284776f41900661182""",
    """title""": """University_of_Notre_Dame""",
    """context""": """Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.""",
    """question""": """To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?""",
    """answers""": {"""text""": ["""Saint Bernadette Soubirous"""], """answer_start""": [515]},
}
@pytest.mark.parametrize(
    """task_cls"""   ,[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]   ,)
def     snake_case_  (       a__		:     str      ):



    """simple docstring"""




    __lowercase          =						task_cls()
    __lowercase          =						asdict(a__      )
    __lowercase          =						task_template_from_dict(a__      )
    assert task == reloaded






class 	SCREAMING_SNAKE_CASE:

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						LanguageModeling(text_column="""input_text"""					)
           assert {"input_text": "text"} == task.column_mapping




       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text"""}
           __lowercase          =						LanguageModeling.from_dict(lowerCamelCase__					)
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{"""text_column""": """input_text""", """label_column""": """input_labels"""}
           __lowercase          =						TextClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""text-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						QuestionAnsweringExtractive(
               context_column="""input_context""" ,		question_column="""input_question""" ,		answers_column="""input_answers"""					)
           self.assertDictEqual(
               {"""input_context""": """context""", """input_question""": """question""", """input_answers""": """answers"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						Features({"""question""": Value("""string"""					), """context""": Value("""string"""					)}					)
           __lowercase          =						Features(
               {
                   """answers""": Sequence(
                       {
                           """text""": Value("""string"""					),
                           """answer_start""": Value("""int32"""					),
                       }					)
               }					)
           __lowercase          =						{
               """context_column""": """input_input_context""",
               """question_column""": """input_question""",
               """answers_column""": """input_answers""",
           }
           __lowercase          =						QuestionAnsweringExtractive.from_dict(lowerCamelCase__					)
           self.assertEqual("""question-answering-extractive""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           __lowercase          =						Summarization(text_column="""input_text""" ,		summary_column="""input_summary"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						Features({"""summary""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
           __lowercase          =						Summarization.from_dict(lowerCamelCase__					)
           self.assertEqual("""summarization""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AutomaticSpeechRecognition(audio_column="""input_audio""" ,		transcription_column="""input_transcription"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""transcription""": Value("""string"""					)}					)
           __lowercase          =						{
               """audio_column""": """input_audio""",
               """transcription_column""": """input_transcription""",
           }
           __lowercase          =						AutomaticSpeechRecognition.from_dict(lowerCamelCase__					)
           self.assertEqual("""automatic-speech-recognition""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

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

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

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

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""} ,		task.column_mapping					)

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

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """audio_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						AudioClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""audio-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

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

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""image""": Image()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """image_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						ImageClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""image-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
           __lowercase          =						Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()} ,		info=lowerCamelCase__					)
           assert isinstance(dataset.info.task_templates ,		lowerCamelCase__					)
           assert len(dataset.info.task_templates					) == 1

           def keep_task(lowerCamelCase__					):
               return x

           def dont_keep_task(lowerCamelCase__					):
               __lowercase          =						deepcopy(lowerCamelCase__					)
               __lowercase          =						0
               return out

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					), """label""": ClassLabel(names=("""pos""", """neg""")					)}					)
           __lowercase          =						TextClassification(text_column="""text""" ,		label_column="""label"""					)
           __lowercase          =						DatasetInfo(features=lowerCamelCase__ ,		task_templates=lowerCamelCase__					)
           __lowercase          =						Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]} ,		info=lowerCamelCase__					)

           def process(lowerCamelCase__					):
               return example

           __lowercase          =						dataset.remove_columns("""label"""					)
           __lowercase          =						modified_dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




