


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


_SCREAMING_SNAKE_CASE :					Union[str, Any]			=	{
    """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 						_lowercase       (     __lowerCamelCase			:					Dict			)  ->   str:





     '''simple docstring'''





     UpperCamelCase__							:  Any								=     task_cls()
     UpperCamelCase__							:  Tuple								=     asdict(__lowerCamelCase			)
     UpperCamelCase__							:  Any								=     task_template_from_dict(__lowerCamelCase			)
     assert task == reloaded

class  UpperCamelCase__ :






      def 	__lowercase(     self					:   Tuple   )  -> List[Any]:
           UpperCamelCase__							:  Optional[Any]								=     LanguageModeling(text_column='''input_text'''   )
           assert {"input_text": "text"} == task.column_mapping






      def 	__lowercase(     self					:   Tuple   )  -> Dict:
           UpperCamelCase__							:  Optional[Any]								=     Features({'''text''': Value('''string'''   )}   )
           UpperCamelCase__							:  Optional[int]								=     {'''text_column''': '''input_text'''}
           UpperCamelCase__							:  Union[str, Any]								=     LanguageModeling.from_dict(UpperCamelCase__   )
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   List[Any]   )  -> Optional[Any]:
           UpperCamelCase__							:  List[str]								=     sorted(['''pos''', '''neg''']   )






      def 	__lowercase(     self					:   str   )  -> int:
           UpperCamelCase__							:  Tuple								=     TextClassification(text_column='''input_text''',		label_column='''input_label'''   )
           self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''},		task.column_mapping   )






      def 	__lowercase(     self					:   int   )  -> int:
           UpperCamelCase__							:  int								=     Features({'''text''': Value('''string'''   )}   )
           # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
           UpperCamelCase__							:  List[str]								=     Features({'''labels''': ClassLabel}   )
           UpperCamelCase__							:  Optional[int]								=     {'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
           UpperCamelCase__							:  Optional[Any]								=     TextClassification.from_dict(UpperCamelCase__   )
           self.assertEqual('''text-classification''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )






      def 	__lowercase(     self					:   List[Any]   )  -> Optional[int]:
           UpperCamelCase__							:  Dict								=     TextClassification(text_column='''input_text''',		label_column='''input_label'''   )
           self.assertEqual(task.label_schema['''labels'''],		UpperCamelCase__   )
           UpperCamelCase__							:  Tuple								=     task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels   )}   )   )
           self.assertEqual(task.label_schema['''labels'''],		ClassLabel(names=self.labels   )   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   List[Any]   )  -> int:
           UpperCamelCase__							:  Union[str, Any]								=     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 	__lowercase(     self					:   Tuple   )  -> Optional[int]:
           UpperCamelCase__							:  Tuple								=     Features({'''question''': Value('''string'''   ), '''context''': Value('''string'''   )}   )
           UpperCamelCase__							:  List[str]								=     Features(
               {
                   '''answers''': Sequence(
                       {
                           '''text''': Value('''string'''   ),
                           '''answer_start''': Value('''int32'''   ),
                       }   )
               }   )
           UpperCamelCase__							:  Optional[int]								=     {
               '''context_column''': '''input_input_context''',
               '''question_column''': '''input_question''',
               '''answers_column''': '''input_answers''',
           }
           UpperCamelCase__							:  Union[str, Any]								=     QuestionAnsweringExtractive.from_dict(UpperCamelCase__   )
           self.assertEqual('''question-answering-extractive''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   Optional[int]   )  -> Any:
           UpperCamelCase__							:  Optional[int]								=     Summarization(text_column='''input_text''',		summary_column='''input_summary'''   )
           self.assertDictEqual({'''input_text''': '''text''', '''input_summary''': '''summary'''},		task.column_mapping   )






      def 	__lowercase(     self					:   List[Any]   )  -> Dict:
           UpperCamelCase__							:  str								=     Features({'''text''': Value('''string'''   )}   )
           UpperCamelCase__							:  int								=     Features({'''summary''': Value('''string'''   )}   )
           UpperCamelCase__							:  int								=     {'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
           UpperCamelCase__							:  Tuple								=     Summarization.from_dict(UpperCamelCase__   )
           self.assertEqual('''summarization''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   List[str]   )  -> Any:
           UpperCamelCase__							:  List[Any]								=     AutomaticSpeechRecognition(audio_column='''input_audio''',		transcription_column='''input_transcription'''   )
           self.assertDictEqual({'''input_audio''': '''audio''', '''input_transcription''': '''transcription'''},		task.column_mapping   )






      def 	__lowercase(     self					:   int   )  -> Tuple:
           UpperCamelCase__							:  List[Any]								=     Features({'''audio''': Audio()}   )
           UpperCamelCase__							:  int								=     Features({'''transcription''': Value('''string'''   )}   )
           UpperCamelCase__							:  Optional[int]								=     {
               '''audio_column''': '''input_audio''',
               '''transcription_column''': '''input_transcription''',
           }
           UpperCamelCase__							:  Union[str, Any]								=     AutomaticSpeechRecognition.from_dict(UpperCamelCase__   )
           self.assertEqual('''automatic-speech-recognition''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   int   )  -> Tuple:
           UpperCamelCase__							:  Dict								=     sorted(['''pos''', '''neg''']   )






      def 	__lowercase(     self					:   List[str]   )  -> Any:
           UpperCamelCase__							:  List[str]								=     AudioClassification(audio_column='''input_audio''',		label_column='''input_label'''   )
           self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''},		task.column_mapping   )






      def 	__lowercase(     self					:   int   )  -> Optional[Any]:
           UpperCamelCase__							:  Union[str, Any]								=     Features({'''audio''': Audio()}   )
           UpperCamelCase__							:  str								=     Features({'''labels''': ClassLabel}   )
           UpperCamelCase__							:  Optional[Any]								=     {
               '''audio_column''': '''input_image''',
               '''label_column''': '''input_label''',
           }
           UpperCamelCase__							:  Union[str, Any]								=     AudioClassification.from_dict(UpperCamelCase__   )
           self.assertEqual('''audio-classification''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )






      def 	__lowercase(     self					:   str   )  -> Union[str, Any]:
           UpperCamelCase__							:  List[str]								=     AudioClassification(audio_column='''input_audio''',		label_column='''input_label'''   )
           self.assertEqual(task.label_schema['''labels'''],		UpperCamelCase__   )
           UpperCamelCase__							:  Tuple								=     task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels   )}   )   )
           self.assertEqual(task.label_schema['''labels'''],		ClassLabel(names=self.labels   )   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   Tuple   )  -> Optional[int]:
           UpperCamelCase__							:  Tuple								=     sorted(['''pos''', '''neg''']   )






      def 	__lowercase(     self					:   Tuple   )  -> int:
           UpperCamelCase__							:  Union[str, Any]								=     ImageClassification(image_column='''input_image''',		label_column='''input_label'''   )
           self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''},		task.column_mapping   )






      def 	__lowercase(     self					:   Tuple   )  -> Tuple:
           UpperCamelCase__							:  Any								=     Features({'''image''': Image()}   )
           UpperCamelCase__							:  Dict								=     Features({'''labels''': ClassLabel}   )
           UpperCamelCase__							:  List[Any]								=     {
               '''image_column''': '''input_image''',
               '''label_column''': '''input_label''',
           }
           UpperCamelCase__							:  int								=     ImageClassification.from_dict(UpperCamelCase__   )
           self.assertEqual('''image-classification''',		task.task   )
           self.assertEqual(UpperCamelCase__,		task.input_schema   )
           self.assertEqual(UpperCamelCase__,		task.label_schema   )






      def 	__lowercase(     self					:   Optional[Any]   )  -> List[str]:
           UpperCamelCase__							:  Optional[int]								=     ImageClassification(image_column='''input_image''',		label_column='''input_label'''   )
           self.assertEqual(task.label_schema['''labels'''],		UpperCamelCase__   )
           UpperCamelCase__							:  List[Any]								=     task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels   )}   )   )
           self.assertEqual(task.label_schema['''labels'''],		ClassLabel(names=self.labels   )   )

class  UpperCamelCase__ ( _SCREAMING_SNAKE_CASE			):






      def 	__lowercase(     self					:   Tuple   )  -> List[Any]:
           UpperCamelCase__							:  int								=     DatasetInfo(task_templates=QuestionAnsweringExtractive()   )
           UpperCamelCase__							:  Union[str, Any]								=     Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()},		info=UpperCamelCase__   )
           assert isinstance(dataset.info.task_templates,		UpperCamelCase__   )
           assert len(dataset.info.task_templates   ) == 1

           def keep_task(__lowerCamelCase					:   Any   ):
                return x

           def dont_keep_task(__lowerCamelCase					:   Union[str, Any]   ):
                UpperCamelCase__							:  Dict								=     deepcopy(UpperCamelCase__   )
                UpperCamelCase__							:  int								=     0
                return out

           UpperCamelCase__							:  str								=     dataset.map(UpperCamelCase__   )
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           UpperCamelCase__							:  Optional[int]								=     dataset.map(UpperCamelCase__   )
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

           UpperCamelCase__							:  Any								=     dataset.map(UpperCamelCase__   )
           assert mapped_dataset.info.task_templates == []
           # reload from cache
           UpperCamelCase__							:  Tuple								=     dataset.map(UpperCamelCase__   )
           assert mapped_dataset.info.task_templates == []






      def 	__lowercase(     self					:   List[Any]   )  -> Dict:
           UpperCamelCase__							:  Union[str, Any]								=     Features({'''text''': Value('''string'''   ), '''label''': ClassLabel(names=('''pos''', '''neg''')   )}   )
           UpperCamelCase__							:  Optional[int]								=     TextClassification(text_column='''text''',		label_column='''label'''   )
           UpperCamelCase__							:  Tuple								=     DatasetInfo(features=UpperCamelCase__,		task_templates=UpperCamelCase__   )
           UpperCamelCase__							:  Tuple								=     Dataset.from_dict({'''text''': ['''A sentence.'''], '''label''': ['''pos''']},		info=UpperCamelCase__   )

           def process(__lowerCamelCase					:   Dict   ):
                return example

           UpperCamelCase__							:  Optional[Any]								=     dataset.remove_columns('''label'''   )
           UpperCamelCase__							:  int								=     modified_dataset.map(UpperCamelCase__   )
           assert mapped_dataset.info.task_templates == []








import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_deberta import DebertaTokenizer


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation


_SCREAMING_SNAKE_CASE :					Tuple			=	logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE :					Tuple			=	{"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

_SCREAMING_SNAKE_CASE :					str			=	{
    """vocab_file""": {
        """microsoft/deberta-base""": """https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json""",
        """microsoft/deberta-large""": """https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json""",
        """microsoft/deberta-xlarge""": """https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json""",
        """microsoft/deberta-base-mnli""": """https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json""",
        """microsoft/deberta-large-mnli""": """https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json""",
        """microsoft/deberta-xlarge-mnli""": (
            """https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json"""
        ),
    },
    """merges_file""": {
        """microsoft/deberta-base""": """https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt""",
        """microsoft/deberta-large""": """https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt""",
        """microsoft/deberta-xlarge""": """https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt""",
        """microsoft/deberta-base-mnli""": """https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt""",
        """microsoft/deberta-large-mnli""": """https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt""",
        """microsoft/deberta-xlarge-mnli""": (
            """https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt"""
        ),
    },
}

_SCREAMING_SNAKE_CASE :					Any			=	{
    """microsoft/deberta-base""": 512,
    """microsoft/deberta-large""": 512,
    """microsoft/deberta-xlarge""": 512,
    """microsoft/deberta-base-mnli""": 512,
    """microsoft/deberta-large-mnli""": 512,
    """microsoft/deberta-xlarge-mnli""": 512,
}

_SCREAMING_SNAKE_CASE :					Any			=	{
    """microsoft/deberta-base""": {"""do_lower_case""": False},
    """microsoft/deberta-large""": {"""do_lower_case""": False},
}

class  UpperCamelCase__ ( __lowerCamelCase			):
      a__   :     int								=						VOCAB_FILES_NAMES
      a__   :     Optional[Any]								=						PRETRAINED_VOCAB_FILES_MAP
      a__   :     int								=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      a__   :     str								=						['input_ids', 'attention_mask', 'token_type_ids']
      a__   :     int								=						DebertaTokenizer






      def __init__(     self					:   Optional[int],		__lowerCamelCase					:   List[str]=None,		__lowerCamelCase					:   Optional[Any]=None,		__lowerCamelCase					:   Union[str, Any]=None,		__lowerCamelCase					:   str="replace",		__lowerCamelCase					:   Any="[CLS]",		__lowerCamelCase					:   Optional[int]="[SEP]",		__lowerCamelCase					:   List[Any]="[SEP]",		__lowerCamelCase					:   Optional[Any]="[CLS]",		__lowerCamelCase					:   List[Any]="[UNK]",		__lowerCamelCase					:   Optional[Any]="[PAD]",		__lowerCamelCase					:   Dict="[MASK]",		__lowerCamelCase					:   List[Any]=False,		**__lowerCamelCase					:   Union[str, Any],		)  -> Optional[int]:
           super().__init__(
               __lowerCamelCase,		__lowerCamelCase,		tokenizer_file=__lowerCamelCase,		errors=__lowerCamelCase,		bos_token=__lowerCamelCase,		eos_token=__lowerCamelCase,		unk_token=__lowerCamelCase,		sep_token=__lowerCamelCase,		cls_token=__lowerCamelCase,		pad_token=__lowerCamelCase,		mask_token=__lowerCamelCase,		add_prefix_space=__lowerCamelCase,		**__lowerCamelCase,		)
           UpperCamelCase__							:  Any								=     kwargs.pop('''add_bos_token''',		__lowerCamelCase   )

           UpperCamelCase__							:  List[Any]								=     json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()   )
           if pre_tok_state.get('''add_prefix_space''',		__lowerCamelCase   ) != add_prefix_space:
                UpperCamelCase__							:  Tuple								=     getattr(__lowerCamelCase,		pre_tok_state.pop('''type'''   )   )
                UpperCamelCase__							:  Tuple								=     add_prefix_space
                UpperCamelCase__							:  Union[str, Any]								=     pre_tok_class(**__lowerCamelCase   )

           UpperCamelCase__							:  Optional[int]								=     add_prefix_space






      @property
      def 	__lowercase(     self					:   Dict   )  -> str:
           if self._mask_token is None:
                if self.verbose:
                     logger.error('''Using mask_token, but it is not set yet.'''   )
                return None
           return str(self._mask_token   )






      @mask_token.setter
      def 	__lowercase(     self					:   List[Any],		__lowerCamelCase					:   Union[str, Any]   )  -> List[str]:
           UpperCamelCase__							:  List[Any]								=     AddedToken(__lowerCamelCase,		lstrip=__lowerCamelCase,		rstrip=__lowerCamelCase   ) if isinstance(__lowerCamelCase,		__lowerCamelCase   ) else value
           UpperCamelCase__							:  List[str]								=     value






      def 	__lowercase(     self					:   List[str],		__lowerCamelCase					:   List[int],		__lowerCamelCase					:   Optional[List[int]] = None   )  -> List[int]:
           if token_ids_a is None:
                return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
           UpperCamelCase__							:  Union[str, Any]								=     [self.cls_token_id]
           UpperCamelCase__							:  Union[str, Any]								=     [self.sep_token_id]
           return cls + token_ids_a + sep + token_ids_a + sep






      def 	__lowercase(     self					:   str,		__lowerCamelCase					:   List[int],		__lowerCamelCase					:   Optional[List[int]] = None   )  -> List[int]:
           UpperCamelCase__							:  Dict								=     [self.sep_token_id]
           UpperCamelCase__							:  int								=     [self.cls_token_id]

           if token_ids_a is None:
                return len(cls + token_ids_a + sep   ) * [0]
           return len(cls + token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]






      def 	__lowercase(     self					:   Union[str, Any],		*__lowerCamelCase					:   Any,		**__lowerCamelCase					:   List[Any]   )  -> BatchEncoding:
           UpperCamelCase__							:  str								=     kwargs.get('''is_split_into_words''',		__lowerCamelCase   )
           assert self.add_prefix_space or not is_split_into_words, (
               f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
               "to use it with pretokenized inputs."
           )

           return super()._batch_encode_plus(*__lowerCamelCase,		**__lowerCamelCase   )






      def 	__lowercase(     self					:   Optional[Any],		*__lowerCamelCase					:   str,		**__lowerCamelCase					:   int   )  -> BatchEncoding:
           UpperCamelCase__							:  str								=     kwargs.get('''is_split_into_words''',		__lowerCamelCase   )

           assert self.add_prefix_space or not is_split_into_words, (
               f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
               "to use it with pretokenized inputs."
           )

           return super()._encode_plus(*__lowerCamelCase,		**__lowerCamelCase   )






      def 	__lowercase(     self					:   Union[str, Any],		__lowerCamelCase					:   str,		__lowerCamelCase					:   Optional[str] = None   )  -> Tuple[str]:
           UpperCamelCase__							:  Dict								=     self._tokenizer.model.save(__lowerCamelCase,		name=__lowerCamelCase   )
           return tuple(__lowerCamelCase   )






      def 	__lowercase(     self					:   int,		__lowerCamelCase					:   "Conversation"   )  -> List[int]:
           UpperCamelCase__							:  List[Any]								=     []
           for is_user, text in conversation.iter_texts():
                input_ids.extend(self.encode(__lowerCamelCase,		add_special_tokens=__lowerCamelCase   ) + [self.eos_token_id]   )

           if len(__lowerCamelCase   ) > self.model_max_length:
                UpperCamelCase__							:  List[Any]								=     input_ids[-self.model_max_length :]
           return input_ids




