


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    :				List[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': [5_15]},
}
@pytest.mark.parametrize(
    '''task_cls'''							,[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]							,)
def     UpperCAmelCase__		(UpperCamelCase_       ):



     """simple docstring"""






     snake_case					=       task_cls()
     snake_case					=       asdict(_SCREAMING_SNAKE_CASE       )
     snake_case					=       task_template_from_dict(_SCREAMING_SNAKE_CASE       )
     assert task == reloaded

class 						A__      :







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       LanguageModeling(text_column='''input_text'''					)
         assert {"input_text": "text"} == task.column_mapping




    def 	a_    ( self					):
         snake_case					=       Features({'''text''': Value('''string'''					)}					)
         snake_case					=       {'text_column': 'input_text'}
         snake_case					=       LanguageModeling.from_dict(__a					)
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       sorted(['''pos''', '''neg''']					)
    def 	a_    ( self					):
         snake_case					=       TextClassification(text_column='''input_text'''    ,      label_column='''input_label'''					)
         self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}    ,      task.column_mapping					)
    def 	a_    ( self					):
         snake_case					=       Features({'''text''': Value('''string'''					)}					)
         # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
         snake_case					=       Features({'''labels''': ClassLabel}					)
         snake_case					=       {'text_column': 'input_text', 'label_column': 'input_labels'}
         snake_case					=       TextClassification.from_dict(__a					)
         self.assertEqual('''text-classification'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)




    def 	a_    ( self					):
         snake_case					=       TextClassification(text_column='''input_text'''    ,      label_column='''input_label'''					)
         self.assertEqual(task.label_schema['''labels''']    ,      __a					)
         snake_case					=       task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels					)}					)					)
         self.assertEqual(task.label_schema['''labels''']    ,      ClassLabel(names=self.labels					)					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       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					):
         snake_case					=       Features({'''question''': Value('''string'''					), '''context''': Value('''string'''					)}					)
         snake_case					=       Features(
             {
                 '''answers''': Sequence(
                     {
                         '''text''': Value('''string'''					),
                         '''answer_start''': Value('''int32'''					),
                     }					)
             }					)
         snake_case					=       {
             'context_column': 'input_input_context',
             'question_column': 'input_question',
             'answers_column': 'input_answers',
         }
         snake_case					=       QuestionAnsweringExtractive.from_dict(__a					)
         self.assertEqual('''question-answering-extractive'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

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




    def 	a_    ( self					):
         snake_case					=       Features({'''text''': Value('''string'''					)}					)
         snake_case					=       Features({'''summary''': Value('''string'''					)}					)
         snake_case					=       {'text_column': 'input_text', 'summary_column': 'input_summary'}
         snake_case					=       Summarization.from_dict(__a					)
         self.assertEqual('''summarization'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       AutomaticSpeechRecognition(audio_column='''input_audio'''    ,      transcription_column='''input_transcription'''					)
         self.assertDictEqual({'''input_audio''': '''audio''', '''input_transcription''': '''transcription'''}    ,      task.column_mapping					)




    def 	a_    ( self					):
         snake_case					=       Features({'''audio''': Audio()}					)
         snake_case					=       Features({'''transcription''': Value('''string'''					)}					)
         snake_case					=       {
             'audio_column': 'input_audio',
             'transcription_column': 'input_transcription',
         }
         snake_case					=       AutomaticSpeechRecognition.from_dict(__a					)
         self.assertEqual('''automatic-speech-recognition'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       sorted(['''pos''', '''neg''']					)
    def 	a_    ( self					):
         snake_case					=       AudioClassification(audio_column='''input_audio'''    ,      label_column='''input_label'''					)
         self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}    ,      task.column_mapping					)
    def 	a_    ( self					):
         snake_case					=       Features({'''audio''': Audio()}					)
         snake_case					=       Features({'''labels''': ClassLabel}					)
         snake_case					=       {
             'audio_column': 'input_image',
             'label_column': 'input_label',
         }
         snake_case					=       AudioClassification.from_dict(__a					)
         self.assertEqual('''audio-classification'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)




    def 	a_    ( self					):
         snake_case					=       AudioClassification(audio_column='''input_audio'''    ,      label_column='''input_label'''					)
         self.assertEqual(task.label_schema['''labels''']    ,      __a					)
         snake_case					=       task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels					)}					)					)
         self.assertEqual(task.label_schema['''labels''']    ,      ClassLabel(names=self.labels					)					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       sorted(['''pos''', '''neg''']					)
    def 	a_    ( self					):
         snake_case					=       ImageClassification(image_column='''input_image'''    ,      label_column='''input_label'''					)
         self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}    ,      task.column_mapping					)
    def 	a_    ( self					):
         snake_case					=       Features({'''image''': Image()}					)
         snake_case					=       Features({'''labels''': ClassLabel}					)
         snake_case					=       {
             'image_column': 'input_image',
             'label_column': 'input_label',
         }
         snake_case					=       ImageClassification.from_dict(__a					)
         self.assertEqual('''image-classification'''    ,      task.task					)
         self.assertEqual(__a    ,      task.input_schema					)
         self.assertEqual(__a    ,      task.label_schema					)




    def 	a_    ( self					):
         snake_case					=       ImageClassification(image_column='''input_image'''    ,      label_column='''input_label'''					)
         self.assertEqual(task.label_schema['''labels''']    ,      __a					)
         snake_case					=       task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels					)}					)					)
         self.assertEqual(task.label_schema['''labels''']    ,      ClassLabel(names=self.labels					)					)






class 						A__      (					lowerCAmelCase_			):







    """simple docstring"""

    def 	a_    ( self					):
         snake_case					=       DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
         snake_case					=       Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}    ,      info=__a					)
         assert isinstance(dataset.info.task_templates    ,      __a					)
         assert len(dataset.info.task_templates					) == 1

         def keep_task(__snake_case					):
              return x

         def dont_keep_task(__snake_case					):
              snake_case					=       deepcopy(__a					)
              snake_case					=       0
              return out

         snake_case					=       dataset.map(__a					)
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         snake_case					=       dataset.map(__a					)
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




    def 	a_    ( self					):
         snake_case					=       Features({'''text''': Value('''string'''					), '''label''': ClassLabel(names=('''pos''', '''neg''')					)}					)
         snake_case					=       TextClassification(text_column='''text'''    ,      label_column='''label'''					)
         snake_case					=       DatasetInfo(features=__a    ,      task_templates=__a					)
         snake_case					=       Dataset.from_dict({'''text''': ['''A sentence.'''], '''label''': ['''pos''']}    ,      info=__a					)

         def process(__snake_case					):
              return example

         snake_case					=       dataset.remove_columns('''label'''					)
         snake_case					=       modified_dataset.map(__a					)
         assert mapped_dataset.info.task_templates == []








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE    :				Optional[int]       =					{
    "configuration_layoutlm": ["LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMConfig", "LayoutLMOnnxConfig"],
    "tokenization_layoutlm": ["LayoutLMTokenizer"],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _SCREAMING_SNAKE_CASE    :				str       =					["LayoutLMTokenizerFast"]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _SCREAMING_SNAKE_CASE    :				List[str]       =					[
     "LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST",
     "LayoutLMForMaskedLM",
     "LayoutLMForSequenceClassification",
     "LayoutLMForTokenClassification",
     "LayoutLMForQuestionAnswering",
     "LayoutLMModel",
     "LayoutLMPreTrainedModel",
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _SCREAMING_SNAKE_CASE    :				Optional[int]       =					[
     "TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST",
     "TFLayoutLMForMaskedLM",
     "TFLayoutLMForSequenceClassification",
     "TFLayoutLMForTokenClassification",
     "TFLayoutLMForQuestionAnswering",
     "TFLayoutLMMainLayer",
     "TFLayoutLMModel",
     "TFLayoutLMPreTrainedModel",
 ]


if TYPE_CHECKING:
 from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMOnnxConfig
 from .tokenization_layoutlm import LayoutLMTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_layoutlm_fast import LayoutLMTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_layoutlm import (
      LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
      LayoutLMForMaskedLM,
      LayoutLMForQuestionAnswering,
      LayoutLMForSequenceClassification,
      LayoutLMForTokenClassification,
      LayoutLMModel,
      LayoutLMPreTrainedModel,
  )
 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_layoutlm import (
      TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFLayoutLMForMaskedLM,
      TFLayoutLMForQuestionAnswering,
      TFLayoutLMForSequenceClassification,
      TFLayoutLMForTokenClassification,
      TFLayoutLMMainLayer,
      TFLayoutLMModel,
      TFLayoutLMPreTrainedModel,
  )

else:
 import sys

 _SCREAMING_SNAKE_CASE    :				Optional[int]       =					_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




