






'''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      :       Optional[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_1_5]},
}


@pytest.mark.parametrize(
    "task_cls"							,			[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]							,			)
def 						_UpperCamelCase							(     snake_case__							):
      __A		   =      task_cls()
      __A		   =      asdict(snake_case__							)
      __A		   =      task_template_from_dict(snake_case__							)
      assert task == reloaded






class 					a__    :
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	Tuple					)  ->       str:
           __A		   =      LanguageModeling(text_column="input_text"					)
           assert {"input_text": "text"} == task.column_mapping






     def     _UpperCamelCase   (self    :	Tuple					)  ->       int:
           __A		   =      Features({"text": Value("string"					)}					)
           __A		   =      {"text_column": "input_text"}
           __A		   =      LanguageModeling.from_dict(UpperCamelCase__					)
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	List[Any]					)  ->       Optional[Any]:
           __A		   =      sorted(["pos", "neg"]					)






     def     _UpperCamelCase   (self    :	str					)  ->       int:
           __A		   =      TextClassification(text_column="input_text"				,				label_column="input_label"					)
           self.assertDictEqual({"input_text": "text", "input_label": "labels"}				,				task.column_mapping					)






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






     def     _UpperCamelCase   (self    :	List[Any]					)  ->       Optional[Any]:
           __A		   =      TextClassification(text_column="input_text"				,				label_column="input_label"					)
           self.assertEqual(task.label_schema["labels"]				,				UpperCamelCase__					)
           __A		   =      task.align_with_features(Features({"input_label": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["labels"]				,				ClassLabel(names=self.labels					)					)







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







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







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	Optional[int]					)  ->       int:
           __A		   =      Summarization(text_column="input_text"				,				summary_column="input_summary"					)
           self.assertDictEqual({"input_text": "text", "input_summary": "summary"}				,				task.column_mapping					)






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







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	List[str]					)  ->       str:
           __A		   =      AutomaticSpeechRecognition(audio_column="input_audio"				,				transcription_column="input_transcription"					)
           self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}				,				task.column_mapping					)






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







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	int					)  ->       List[str]:
           __A		   =      sorted(["pos", "neg"]					)






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






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






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







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	Tuple					)  ->       Optional[Any]:
           __A		   =      sorted(["pos", "neg"]					)






     def     _UpperCamelCase   (self    :	Tuple					)  ->       str:
           __A		   =      ImageClassification(image_column="input_image"				,				label_column="input_label"					)
           self.assertDictEqual({"input_image": "image", "input_label": "labels"}				,				task.column_mapping					)






     def     _UpperCamelCase   (self    :	Tuple					)  ->       int:
           __A		   =      Features({"image": Image()}					)
           __A		   =      Features({"labels": ClassLabel}					)
           __A		   =      {
               "image_column": "input_image",
               "label_column": "input_label",
           }
           __A		   =      ImageClassification.from_dict(UpperCamelCase__					)
           self.assertEqual("image-classification"				,				task.task					)
           self.assertEqual(UpperCamelCase__				,				task.input_schema					)
           self.assertEqual(UpperCamelCase__				,				task.label_schema					)






     def     _UpperCamelCase   (self    :	Optional[Any]					)  ->       Tuple:
           __A		   =      ImageClassification(image_column="input_image"				,				label_column="input_label"					)
           self.assertEqual(task.label_schema["labels"]				,				UpperCamelCase__					)
           __A		   =      task.align_with_features(Features({"input_label": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["labels"]				,				ClassLabel(names=self.labels					)					)







class 					a__    (			_SCREAMING_SNAKE_CASE						):
     '''simple docstring'''







     def     _UpperCamelCase   (self    :	Tuple					)  ->       Union[str, Any]:
           __A		   =      DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
           __A		   =      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(lowercase__    :	Any					):
                 return x

           def dont_keep_task(lowercase__    :	Union[str, Any]					):
                 __A		   =      deepcopy(UpperCamelCase__					)
                 __A		   =      0
                 return out

           __A		   =      dataset.map(UpperCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           __A		   =      dataset.map(UpperCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

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






     def     _UpperCamelCase   (self    :	List[Any]					)  ->       Tuple:
           __A		   =      Features({"text": Value("string"					), "label": ClassLabel(names=("pos", "neg")					)}					)
           __A		   =      TextClassification(text_column="text"				,				label_column="label"					)
           __A		   =      DatasetInfo(features=UpperCamelCase__				,				task_templates=UpperCamelCase__					)
           __A		   =      Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}				,				info=UpperCamelCase__					)

           def process(lowercase__    :	Dict					):
                 return example

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










'''simple docstring'''







import copy
import inspect

from transformers.testing_utils import require_torch, torch_device
from transformers.utils.backbone_utils import BackboneType






@require_torch
class 					a__    :
     '''simple docstring'''







     _snake_case             =  ()
     _snake_case             =  True






     def     _UpperCamelCase   (self    :	Optional[Any]					)  ->       Union[str, Any]:
           __A		   =      self.config_class

           # test default config
           __A		   =      config_class()
           self.assertIsNotNone(lowercase__					)
           __A		   =      ["stem"] + [f"stage{idx}" for idx in range(1				,				len(config.depths					) + 1					)]
           self.assertEqual(config.stage_names				,				lowercase__					)
           self.assertTrue(set(config.out_features					).issubset(set(config.stage_names					)					)					)

           # Test out_features and out_indices are correctly set
           # out_features and out_indices both None
           __A		   =      config_class(out_features=lowercase__				,				out_indices=lowercase__					)
           self.assertEqual(config.out_features				,				[config.stage_names[-1]]					)
           self.assertEqual(config.out_indices				,				[len(config.stage_names					) - 1]					)

           # out_features and out_indices both set
           __A		   =      config_class(out_features=["stem", "stage1"]				,				out_indices=[0, 1]					)
           self.assertEqual(config.out_features				,				["stem", "stage1"]					)
           self.assertEqual(config.out_indices				,				[0, 1]					)

           # Only out_features set
           __A		   =      config_class(out_features=["stage1", "stage3"]					)
           self.assertEqual(config.out_features				,				["stage1", "stage3"]					)
           self.assertEqual(config.out_indices				,				[1, 3]					)

           # Only out_indices set
           __A		   =      config_class(out_indices=[0, 2]					)
           self.assertEqual(config.out_features				,				[config.stage_names[0], config.stage_names[2]]					)
           self.assertEqual(config.out_indices				,				[0, 2]					)

           # Error raised when out_indices do not correspond to out_features
           with self.assertRaises(lowercase__					):
                 __A		   =      config_class(out_features=["stage1", "stage2"]				,				out_indices=[0, 2]					)






     def     _UpperCamelCase   (self    :	Optional[int]					)  ->       Optional[Any]:
           __A   ,				__A		   =      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 __A		   =      model_class(lowercase__					)
                 __A		   =      inspect.signature(model.forward					)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 __A		   =      [*signature.parameters.keys()]
                 __A		   =      ["pixel_values"]
                 self.assertListEqual(arg_names[:1]				,				lowercase__					)






     def     _UpperCamelCase   (self    :	Dict					)  ->       Union[str, Any]:
           __A   ,				__A		   =      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 __A		   =      model_class(lowercase__					)
                 self.assertEqual(len(model.channels					)				,				len(config.out_features					)					)
                 __A		   =      model.num_features
                 __A		   =      [config.stage_names.index(lowercase__					) for feat in config.out_features]
                 __A		   =      [num_features[idx] for idx in out_indices]
                 self.assertListEqual(model.channels				,				lowercase__					)

                 __A		   =      copy.deepcopy(lowercase__					)
                 __A		   =      None
                 __A		   =      model_class(lowercase__					)
                 self.assertEqual(len(model.channels					)				,				1					)
                 self.assertListEqual(model.channels				,				[num_features[-1]]					)

                 __A		   =      copy.deepcopy(lowercase__					)
                 __A		   =      None
                 __A		   =      model_class(lowercase__					)
                 self.assertEqual(len(model.channels					)				,				1					)
                 self.assertListEqual(model.channels				,				[num_features[-1]]					)






     def     _UpperCamelCase   (self    :	Optional[Any]					)  ->       Optional[Any]:
           __A   ,				__A		   =      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 __A		   =      model_class(lowercase__					)
                 model.to(lowercase__					)
                 model.eval()
                 __A		   =      model(**lowercase__					)

                 self.assertEqual(len(result.feature_maps					)				,				len(config.out_features					)					)
                 self.assertEqual(len(model.channels					)				,				len(config.out_features					)					)
                 self.assertEqual(len(result.feature_maps					)				,				len(config.out_indices					)					)
                 self.assertEqual(len(model.channels					)				,				len(config.out_indices					)					)

                 # Check output of last stage is taken if out_features=None, out_indices=None
                 __A		   =      copy.deepcopy(lowercase__					)
                 __A		   =      None
                 __A		   =      model_class(lowercase__					)
                 model.to(lowercase__					)
                 model.eval()
                 __A		   =      model(**lowercase__					)

                 self.assertEqual(len(result.feature_maps					)				,				1					)
                 self.assertEqual(len(model.channels					)				,				1					)

                 __A		   =      copy.deepcopy(lowercase__					)
                 __A		   =      None
                 __A		   =      model_class(lowercase__					)
                 model.to(lowercase__					)
                 model.eval()
                 __A		   =      model(**lowercase__					)

                 self.assertEqual(len(result.feature_maps					)				,				1					)
                 self.assertEqual(len(model.channels					)				,				1					)

                 # Check backbone can be initialized with fresh weights
                 __A		   =      copy.deepcopy(lowercase__					)
                 __A		   =      False
                 __A		   =      model_class(lowercase__					)
                 model.to(lowercase__					)
                 model.eval()
                 __A		   =      model(**lowercase__					)






     def     _UpperCamelCase   (self    :	Dict					)  ->       Optional[int]:
           __A   ,				__A		   =      self.model_tester.prepare_config_and_inputs_for_common()

           for backbone_class in self.all_model_classes:
                 __A		   =      backbone_class(lowercase__					)

                 self.assertTrue(hasattr(lowercase__				,				"backbone_type"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"stage_names"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"num_features"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"out_indices"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"out_features"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"out_feature_channels"					)					)
                 self.assertTrue(hasattr(lowercase__				,				"channels"					)					)

                 self.assertIsInstance(backbone.backbone_type				,				lowercase__					)
                 # Verify num_features has been initialized in the backbone init
                 self.assertIsNotNone(backbone.num_features					)
                 self.assertTrue(len(backbone.channels					) == len(backbone.out_indices					)					)
                 self.assertTrue(len(backbone.stage_names					) == len(backbone.num_features					)					)
                 self.assertTrue(len(backbone.channels					) <= len(backbone.num_features					)					)
                 self.assertTrue(len(backbone.out_feature_channels					) == len(backbone.stage_names					)					)






     def     _UpperCamelCase   (self    :	Tuple					)  ->       int:
           __A   ,				__A		   =      self.model_tester.prepare_config_and_inputs_for_common()
           __A		   =      inputs_dict["pixel_values"].shape[0]

           for backbone_class in self.all_model_classes:
                 __A		   =      backbone_class(lowercase__					)
                 backbone.to(lowercase__					)
                 backbone.eval()

                 __A		   =      backbone(**lowercase__					)

                 # Test default outputs and verify feature maps
                 self.assertIsInstance(outputs.feature_maps				,				lowercase__					)
                 self.assertTrue(len(outputs.feature_maps					) == len(backbone.channels					)					)
                 for feature_map, n_channels in zip(outputs.feature_maps				,				backbone.channels					):
                       self.assertTrue(feature_map.shape[:2]				,				(batch_size, n_channels)					)
                 self.assertIsNone(outputs.hidden_states					)
                 self.assertIsNone(outputs.attentions					)

                 # Test output_hidden_states=True
                 __A		   =      backbone(**lowercase__				,				output_hidden_states=lowercase__					)
                 self.assertIsNotNone(outputs.hidden_states					)
                 self.assertTrue(len(outputs.hidden_states					)				,				len(backbone.stage_names					)					)
                 for hidden_state, n_channels in zip(outputs.hidden_states				,				backbone.channels					):
                       self.assertTrue(hidden_state.shape[:2]				,				(batch_size, n_channels)					)

                 # Test output_attentions=True
                 if self.has_attentions:
                       __A		   =      backbone(**lowercase__				,				output_attentions=lowercase__					)
                       self.assertIsNotNone(outputs.attentions					)


