






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      (UpperCAmelCase__						) ->       List[str]:
  UpperCamelCase_:      Dict					   =       task_cls()
  UpperCamelCase_:      Optional[Any]					   =       asdict(UpperCAmelCase__						)
  UpperCamelCase_:      Optional[int]					   =       task_template_from_dict(UpperCAmelCase__						)
  assert task == reloaded




class        _lowerCAmelCase:





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      int					   =       LanguageModeling(text_column='input_text'							)
         assert {"input_text": "text"} == task.column_mapping





       def     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       Features({'text': Value('string'							)}							)
         UpperCamelCase_:      str					   =       {'text_column': 'input_text'}
         UpperCamelCase_:      Union[str, Any]					   =       LanguageModeling.from_dict(_lowerCamelCase							)
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      Union[str, Any]					   =       sorted(['pos', 'neg']							)





       def     _a					(      self							):
         UpperCamelCase_:      int					   =       TextClassification(text_column='input_text'						,    label_column='input_label'							)
         self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}						,    task.column_mapping							)





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





       def     _a					(      self							):
         UpperCamelCase_:      Union[str, Any]					   =       TextClassification(text_column='input_text'						,    label_column='input_label'							)
         self.assertEqual(task.label_schema['labels']						,    _lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels							)}							)							)
         self.assertEqual(task.label_schema['labels']						,    ClassLabel(names=self.labels							)							)







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







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







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       Summarization(text_column='input_text'						,    summary_column='input_summary'							)
         self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}						,    task.column_mapping							)





       def     _a					(      self							):
         UpperCamelCase_:      str					   =       Features({'text': Value('string'							)}							)
         UpperCamelCase_:      Optional[Any]					   =       Features({'summary': Value('string'							)}							)
         UpperCamelCase_:      Tuple					   =       {'text_column': 'input_text', 'summary_column': 'input_summary'}
         UpperCamelCase_:      Union[str, Any]					   =       Summarization.from_dict(_lowerCamelCase							)
         self.assertEqual('summarization'						,    task.task							)
         self.assertEqual(_lowerCamelCase						,    task.input_schema							)
         self.assertEqual(_lowerCamelCase						,    task.label_schema							)







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      List[Any]					   =       AutomaticSpeechRecognition(audio_column='input_audio'						,    transcription_column='input_transcription'							)
         self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}						,    task.column_mapping							)





       def     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       Features({'audio': Audio()}							)
         UpperCamelCase_:      Dict					   =       Features({'transcription': Value('string'							)}							)
         UpperCamelCase_:      Union[str, Any]					   =       {
             'audio_column': 'input_audio',
             'transcription_column': 'input_transcription',
         }
         UpperCamelCase_:      Dict					   =       AutomaticSpeechRecognition.from_dict(_lowerCamelCase							)
         self.assertEqual('automatic-speech-recognition'						,    task.task							)
         self.assertEqual(_lowerCamelCase						,    task.input_schema							)
         self.assertEqual(_lowerCamelCase						,    task.label_schema							)







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      int					   =       sorted(['pos', 'neg']							)





       def     _a					(      self							):
         UpperCamelCase_:      str					   =       AudioClassification(audio_column='input_audio'						,    label_column='input_label'							)
         self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}						,    task.column_mapping							)





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





       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       AudioClassification(audio_column='input_audio'						,    label_column='input_label'							)
         self.assertEqual(task.label_schema['labels']						,    _lowerCamelCase							)
         UpperCamelCase_:      Any					   =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels							)}							)							)
         self.assertEqual(task.label_schema['labels']						,    ClassLabel(names=self.labels							)							)







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       sorted(['pos', 'neg']							)





       def     _a					(      self							):
         UpperCamelCase_:      Tuple					   =       ImageClassification(image_column='input_image'						,    label_column='input_label'							)
         self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}						,    task.column_mapping							)





       def     _a					(      self							):
         UpperCamelCase_:      int					   =       Features({'image': Image()}							)
         UpperCamelCase_:      Optional[Any]					   =       Features({'labels': ClassLabel}							)
         UpperCamelCase_:      List[str]					   =       {
             'image_column': 'input_image',
             'label_column': 'input_label',
         }
         UpperCamelCase_:      List[Any]					   =       ImageClassification.from_dict(_lowerCamelCase							)
         self.assertEqual('image-classification'						,    task.task							)
         self.assertEqual(_lowerCamelCase						,    task.input_schema							)
         self.assertEqual(_lowerCamelCase						,    task.label_schema							)





       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       ImageClassification(image_column='input_image'						,    label_column='input_label'							)
         self.assertEqual(task.label_schema['labels']						,    _lowerCamelCase							)
         UpperCamelCase_:      Optional[Any]					   =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels							)}							)							)
         self.assertEqual(task.label_schema['labels']						,    ClassLabel(names=self.labels							)							)







class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def     _a					(      self							):
         UpperCamelCase_:      str					   =       DatasetInfo(task_templates=QuestionAnsweringExtractive()							)
         UpperCamelCase_:      str					   =       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							):
           UpperCamelCase_:      Union[str, Any]					   =       deepcopy(_lowerCamelCase							)
           UpperCamelCase_:      Dict					   =       0
           return out

         UpperCamelCase_:      Any					   =       dataset.map(_lowerCamelCase							)
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         UpperCamelCase_:      Union[str, Any]					   =       dataset.map(_lowerCamelCase							)
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

         UpperCamelCase_:      Dict					   =       dataset.map(_lowerCamelCase							)
         assert mapped_dataset.info.task_templates == []
         # reload from cache
         UpperCamelCase_:      Any					   =       dataset.map(_lowerCamelCase							)
         assert mapped_dataset.info.task_templates == []





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

         def process(_lowerCamelCase							):
           return example

         UpperCamelCase_:      str					   =       dataset.remove_columns('label'							)
         UpperCamelCase_:      Dict					   =       modified_dataset.map(_lowerCamelCase							)
         assert mapped_dataset.info.task_templates == []







import os
from shutil import copyfile
from typing import Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
   from .tokenization_reformer import ReformerTokenizer
else:
   A_	:	Union[str, Any]				=				None


A_	:	List[Any]				=				logging.get_logger(__name__)


A_	:	List[str]				=				'▁'

A_	:	int				=				{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

A_	:	Optional[Any]				=				{
    'vocab_file': {
        'google/reformer-crime-and-punishment': (
            'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'
        )
    },
    'tokenizer_file': {
        'google/reformer-crime-and-punishment': (
            'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/tokenizer.json'
        )
    },
}

A_	:	List[Any]				=				{
    'google/reformer-crime-and-punishment': 524288,
}




class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       a       :	int								=VOCAB_FILES_NAMES
       a       :	Optional[Any]								=PRETRAINED_VOCAB_FILES_MAP
       a       :	List[Any]								=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       a       :	Tuple								=['''input_ids''', '''attention_mask''']
       a       :	Optional[Any]								=ReformerTokenizer





       def __init__(      self						,    _lowerCamelCase=None						,    _lowerCamelCase=None						,    _lowerCamelCase="</s>"						,    _lowerCamelCase="<unk>"						,    _lowerCamelCase=[]						,    **_lowerCamelCase						,    ):
         super().__init__(
             _lowerCamelCase						,    tokenizer_file=_lowerCamelCase						,    eos_token=_lowerCamelCase						,    unk_token=_lowerCamelCase						,    additional_special_tokens=_lowerCamelCase						,    **_lowerCamelCase						,    )

         UpperCamelCase_:      Any					   =       vocab_file
         UpperCamelCase_:      str					   =       False if not self.vocab_file else True





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase = None							):
         if not self.can_save_slow_tokenizer:
           raise ValueError(
               'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
               'tokenizer.'							)

         if not os.path.isdir(_lowerCamelCase							):
           logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''							)
           return
         UpperCamelCase_:      str					   =       os.path.join(
             _lowerCamelCase						,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)

         if os.path.abspath(self.vocab_file							) != os.path.abspath(_lowerCamelCase							):
           copyfile(self.vocab_file						,    _lowerCamelCase							)

         return (out_vocab_file,)