





"""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


_lowerCamelCase       =	{
    '''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 		lowerCAmelCase_	(  lowercase_   :							Tuple		):

 '''simple docstring'''






 __SCREAMING_SNAKE_CASE :			Optional[Any]												=       task_cls()
 __SCREAMING_SNAKE_CASE :			Optional[Any]												=       asdict(lowercase_		)
 __SCREAMING_SNAKE_CASE :			Optional[Any]												=       task_template_from_dict(lowercase_		)
 assert task == reloaded





class 			snake_case		:

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						):
       __SCREAMING_SNAKE_CASE :			Tuple												=       LanguageModeling(text_column='''input_text'''						)
       assert {"input_text": "text"} == task.column_mapping



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







class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :Dict						):
       __SCREAMING_SNAKE_CASE :			int												=       sorted(['''pos''', '''neg''']						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :str						):
       __SCREAMING_SNAKE_CASE :			List[str]												=       TextClassification(text_column='''input_text'''						,							label_column='''input_label'''						)
       self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}						,							task.column_mapping						)

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



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







class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :Optional[int]						):
       __SCREAMING_SNAKE_CASE :			Optional[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 						SCREAMING_SNAKE_CASE_			(			self   :str						):
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       Features({'''question''': Value('''string'''						), '''context''': Value('''string'''						)}						)
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       Features(
           {
               '''answers''': Sequence(
                   {
                       '''text''': Value('''string'''						),
                       '''answer_start''': Value('''int32'''						),
                   }						)
           }						)
       __SCREAMING_SNAKE_CASE :			str												=       {
           '''context_column''': '''input_input_context''',
           '''question_column''': '''input_question''',
           '''answers_column''': '''input_answers''',
       }
       __SCREAMING_SNAKE_CASE :			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 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :Dict						):
       __SCREAMING_SNAKE_CASE :			List[Any]												=       Summarization(text_column='''input_text'''						,							summary_column='''input_summary'''						)
       self.assertDictEqual({'''input_text''': '''text''', '''input_summary''': '''summary'''}						,							task.column_mapping						)



      def 						SCREAMING_SNAKE_CASE_			(			self   :List[Any]						):
       __SCREAMING_SNAKE_CASE :			int												=       Features({'''text''': Value('''string'''						)}						)
       __SCREAMING_SNAKE_CASE :			List[str]												=       Features({'''summary''': Value('''string'''						)}						)
       __SCREAMING_SNAKE_CASE :			Any												=       {'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
       __SCREAMING_SNAKE_CASE :			str												=       Summarization.from_dict(_lowerCamelCase						)
       self.assertEqual('''summarization'''						,							task.task						)
       self.assertEqual(_lowerCamelCase						,							task.input_schema						)
       self.assertEqual(_lowerCamelCase						,							task.label_schema						)







class 			snake_case		(   __UpperCAmelCase   ):

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



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







class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :List[Any]						):
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       sorted(['''pos''', '''neg''']						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Optional[Any]						):
       __SCREAMING_SNAKE_CASE :			Any												=       AudioClassification(audio_column='''input_audio'''						,							label_column='''input_label'''						)
       self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}						,							task.column_mapping						)

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



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







class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :Optional[int]						):
       __SCREAMING_SNAKE_CASE :			str												=       sorted(['''pos''', '''neg''']						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE :			int												=       ImageClassification(image_column='''input_image'''						,							label_column='''input_label'''						)
       self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}						,							task.column_mapping						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						):
       __SCREAMING_SNAKE_CASE :			Any												=       Features({'''image''': Image()}						)
       __SCREAMING_SNAKE_CASE :			Dict												=       Features({'''labels''': ClassLabel}						)
       __SCREAMING_SNAKE_CASE :			Any												=       {
           '''image_column''': '''input_image''',
           '''label_column''': '''input_label''',
       }
       __SCREAMING_SNAKE_CASE :			Any												=       ImageClassification.from_dict(_lowerCamelCase						)
       self.assertEqual('''image-classification'''						,							task.task						)
       self.assertEqual(_lowerCamelCase						,							task.input_schema						)
       self.assertEqual(_lowerCamelCase						,							task.label_schema						)



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







class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :List[Any]						):
       __SCREAMING_SNAKE_CASE :			int												=       DatasetInfo(task_templates=QuestionAnsweringExtractive()						)
       __SCREAMING_SNAKE_CASE :			Any												=       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   :Any						):
        return x

       def dont_keep_task(_lowerCamelCase   :Dict						):
        __SCREAMING_SNAKE_CASE :			int												=       deepcopy(_lowerCamelCase						)
        __SCREAMING_SNAKE_CASE :			List[Any]												=       0
        return out

       __SCREAMING_SNAKE_CASE :			Optional[int]												=       dataset.map(_lowerCamelCase						)
       assert mapped_dataset.info.task_templates == dataset.info.task_templates
       # reload from cache
       __SCREAMING_SNAKE_CASE :			List[Any]												=       dataset.map(_lowerCamelCase						)
       assert mapped_dataset.info.task_templates == dataset.info.task_templates

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



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

       def process(_lowerCamelCase   :int						):
        return example

       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       dataset.remove_columns('''label'''						)
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       modified_dataset.map(_lowerCamelCase						)
       assert mapped_dataset.info.task_templates == []




'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor
class 	SCREAMING_SNAKE_CASE__			(				unittest.TestCase      ):




    def __init__(					self				,     lowercase__				,     lowercase__=7				,     lowercase__=3				,     lowercase__=18				,     lowercase__=30				,     lowercase__=400				,     lowercase__=True				,     lowercase__=None				,     lowercase__=True				,     lowercase__=None				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       size if size is not None else {"shortest_edge": 20}
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       crop_size if crop_size is not None else {"height": 18, "width": 18}
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       parent
          SCREAMING_SNAKE_CASE_      :			Tuple     =       batch_size
          SCREAMING_SNAKE_CASE_      :			int     =       num_channels
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       image_size
          SCREAMING_SNAKE_CASE_      :			Dict     =       min_resolution
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       max_resolution
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       do_resize
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       size
          SCREAMING_SNAKE_CASE_      :			Tuple     =       do_center_crop
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       crop_size







    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
          }






@require_torch
@require_vision
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase,unittest.TestCase      ):
    _A			    =							MobileNetVaImageProcessor if is_vision_available() else None




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Any     =       MobileNetVaImageProcessingTester(self			)




    @property
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return self.image_processor_tester.prepare_image_processor_dict()




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class(**self.image_processor_dict			)
          self.assertTrue(hasattr(lowercase__				,     "do_resize"			)			)
          self.assertTrue(hasattr(lowercase__				,     "size"			)			)
          self.assertTrue(hasattr(lowercase__				,     "do_center_crop"			)			)
          self.assertTrue(hasattr(lowercase__				,     "center_crop"			)			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class.from_dict(self.image_processor_dict			)
          self.assertEqual(image_processor.size				,     {"shortest_edge": 20}			)
          self.assertEqual(image_processor.crop_size				,     {"height": 18, "width": 18}			)

          SCREAMING_SNAKE_CASE_      :			List[str]     =       self.image_processing_class.from_dict(self.image_processor_dict				,     size=42				,     crop_size=84			)
          self.assertEqual(image_processor.size				,     {"shortest_edge": 42}			)
          self.assertEqual(image_processor.crop_size				,     {"height": 84, "width": 84}			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random PIL images
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     Image.Image			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random numpy tensors
          SCREAMING_SNAKE_CASE_      :			Dict     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__				,     numpify=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     np.ndarray			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Dict     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			Dict     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )







    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random PyTorch tensors
          SCREAMING_SNAKE_CASE_      :			Any     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__				,     torchify=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     torch.Tensor			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			List[str]     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

