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 ConvNextImageProcessor




class 				__lowerCAmelCase					(    unittest.TestCase  ):



 '''simple docstring'''

 def __init__(     self    :						Tuple    ,     lowerCamelCase    :						str    ,     lowerCamelCase    :						Optional[int]=7    ,     lowerCamelCase    :						int=3    ,     lowerCamelCase    :						str=1_8    ,     lowerCamelCase    :						Dict=3_0    ,     lowerCamelCase    :						Any=4_0_0    ,     lowerCamelCase    :						Tuple=True    ,     lowerCamelCase    :						Optional[int]=None    ,     lowerCamelCase    :						Optional[int]=0.8_7_5    ,     lowerCamelCase    :						Dict=True    ,     lowerCamelCase    :						str=[0.5, 0.5, 0.5]    ,     lowerCamelCase    :						List[Any]=[0.5, 0.5, 0.5]    ,     )	->							Union[str, Any]:
        _UpperCamelCase       :    Any					  =					size if size is not None else {'shortest_edge': 2_0}
        _UpperCamelCase       :    Dict					  =					parent
        _UpperCamelCase       :    Union[str, Any]					  =					batch_size
        _UpperCamelCase       :    List[str]					  =					num_channels
        _UpperCamelCase       :    Any					  =					image_size
        _UpperCamelCase       :    Tuple					  =					min_resolution
        _UpperCamelCase       :    List[Any]					  =					max_resolution
        _UpperCamelCase       :    Union[str, Any]					  =					do_resize
        _UpperCamelCase       :    int					  =					size
        _UpperCamelCase       :    Optional[Any]					  =					crop_pct
        _UpperCamelCase       :    Any					  =					do_normalize
        _UpperCamelCase       :    Any					  =					image_mean
        _UpperCamelCase       :    Optional[int]					  =					image_std

 def    __snake_case   (     self    :						Union[str, Any]					)	->							int:
        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
            "crop_pct": self.crop_pct,
        }







@require_torch
@require_vision
class 				__lowerCAmelCase					(    a_,		unittest.TestCase  ):



 '''simple docstring'''
 _lowerCamelCase  :		Any			      =	ConvNextImageProcessor if is_vision_available() else None

 def    __snake_case   (     self    :						Optional[int]					)	->							Dict:
        _UpperCamelCase       :    List[Any]					  =					ConvNextImageProcessingTester(self					)

 @property
 def    __snake_case   (     self    :						Dict					)	->							Tuple:
        return self.image_processor_tester.prepare_image_processor_dict()

 def    __snake_case   (     self    :						str					)	->							Any:
        _UpperCamelCase       :    int					  =					self.image_processing_class(**self.image_processor_dict					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'do_resize'					)					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'size'					)					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'crop_pct'					)					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'do_normalize'					)					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'image_mean'					)					)
        self.assertTrue(hasattr(lowerCamelCase    ,     'image_std'					)					)

 def    __snake_case   (     self    :						List[str]					)	->							Any:
        _UpperCamelCase       :    Optional[int]					  =					self.image_processing_class.from_dict(self.image_processor_dict					)
        self.assertEqual(image_processor.size    ,     {'shortest_edge': 2_0}					)

        _UpperCamelCase       :    Optional[int]					  =					self.image_processing_class.from_dict(self.image_processor_dict    ,     size=4_2					)
        self.assertEqual(image_processor.size    ,     {'shortest_edge': 4_2}					)

 def    __snake_case   (     self    :						Optional[Any]					)	->							str:
        pass

 def    __snake_case   (     self    :						str					)	->							Union[str, Any]:
        # Initialize image_processing
        _UpperCamelCase       :    str					  =					self.image_processing_class(**self.image_processor_dict					)
        # create random PIL images
        _UpperCamelCase       :    Tuple					  =					prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=lowerCamelCase					)
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase    ,     Image.Image					)

        # Test not batched input
        _UpperCamelCase       :    Optional[Any]					  =					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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )

        # Test batched
        _UpperCamelCase       :    str					  =					image_processing(lowerCamelCase    ,     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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )

 def    __snake_case   (     self    :						Optional[Any]					)	->							str:
        # Initialize image_processing
        _UpperCamelCase       :    Any					  =					self.image_processing_class(**self.image_processor_dict					)
        # create random numpy tensors
        _UpperCamelCase       :    Tuple					  =					prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=lowerCamelCase    ,     numpify=lowerCamelCase					)
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase    ,     np.ndarray					)

        # Test not batched input
        _UpperCamelCase       :    Optional[Any]					  =					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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )

        # Test batched
        _UpperCamelCase       :    int					  =					image_processing(lowerCamelCase    ,     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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )

 def    __snake_case   (     self    :						List[str]					)	->							List[str]:
        # Initialize image_processing
        _UpperCamelCase       :    Optional[int]					  =					self.image_processing_class(**self.image_processor_dict					)
        # create random PyTorch tensors
        _UpperCamelCase       :    Tuple					  =					prepare_image_inputs(self.image_processor_tester    ,     equal_resolution=lowerCamelCase    ,     torchify=lowerCamelCase					)
        for image in image_inputs:
               self.assertIsInstance(lowerCamelCase    ,     torch.Tensor					)

        # Test not batched input
        _UpperCamelCase       :    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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )

        # Test batched
        _UpperCamelCase       :    List[Any]					  =					image_processing(lowerCamelCase    ,     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.size['shortest_edge'],
                self.image_processor_tester.size['shortest_edge'],
            )    ,     )




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


UpperCAmelCase     						=			{
    '''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 SCREAMING_SNAKE_CASE			(       lowercase_:		Optional[int]			):
       _UpperCamelCase       :    int					  =					task_cls()
       _UpperCamelCase       :    List[Any]					  =					asdict(lowercase_			)
       _UpperCamelCase       :    Union[str, Any]					  =					task_template_from_dict(lowercase_			)
       assert task == reloaded




class 				__lowerCAmelCase					:



 '''simple docstring'''

 def    __snake_case   (     self    :						Dict					)	->							Any:
        _UpperCamelCase       :    List[Any]					  =					LanguageModeling(text_column='input_text'					)
        assert {"input_text": "text"} == task.column_mapping

 def    __snake_case   (     self    :						List[Any]					)	->							List[Any]:
        _UpperCamelCase       :    List[str]					  =					Features({'text': Value('string'					)}					)
        _UpperCamelCase       :    Optional[int]					  =					{'text_column': 'input_text'}
        _UpperCamelCase       :    Optional[Any]					  =					LanguageModeling.from_dict(lowerCamelCase					)
        assert "language-modeling" == task.task
        assert input_schema == task.input_schema







class 				__lowerCAmelCase					(    a_  ):



 '''simple docstring'''

 def    __snake_case   (     self    :						List[Any]					)	->							Union[str, Any]:
        _UpperCamelCase       :    Union[str, Any]					  =					sorted(['pos', 'neg']					)

 def    __snake_case   (     self    :						List[str]					)	->							Dict:
        _UpperCamelCase       :    List[str]					  =					TextClassification(text_column='input_text'    ,     label_column='input_label'					)
        self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}    ,     task.column_mapping					)

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

 def    __snake_case   (     self    :						str					)	->							Optional[int]:
        _UpperCamelCase       :    Any					  =					TextClassification(text_column='input_text'    ,     label_column='input_label'					)
        self.assertEqual(task.label_schema['labels']    ,     lowerCamelCase					)
        _UpperCamelCase       :    str					  =					task.align_with_features(Features({'input_label': ClassLabel(names=self.labels					)}					)					)
        self.assertEqual(task.label_schema['labels']    ,     ClassLabel(names=self.labels					)					)







class 				__lowerCAmelCase					(    a_  ):



 '''simple docstring'''

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



 '''simple docstring'''

 def    __snake_case   (     self    :						Optional[Any]					)	->							List[str]:
        _UpperCamelCase       :    List[str]					  =					Summarization(text_column='input_text'    ,     summary_column='input_summary'					)
        self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}    ,     task.column_mapping					)

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







class 				__lowerCAmelCase					(    a_  ):



 '''simple docstring'''

 def    __snake_case   (     self    :						Any					)	->							Optional[int]:
        _UpperCamelCase       :    Dict					  =					AutomaticSpeechRecognition(audio_column='input_audio'    ,     transcription_column='input_transcription'					)
        self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}    ,     task.column_mapping					)

 def    __snake_case   (     self    :						List[Any]					)	->							int:
        _UpperCamelCase       :    Union[str, Any]					  =					Features({'audio': Audio()}					)
        _UpperCamelCase       :    Any					  =					Features({'transcription': Value('string'					)}					)
        _UpperCamelCase       :    Optional[int]					  =					{
            'audio_column': 'input_audio',
            'transcription_column': 'input_transcription',
        }
        _UpperCamelCase       :    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 				__lowerCAmelCase					(    a_  ):



 '''simple docstring'''

 def    __snake_case   (     self    :						Union[str, Any]					)	->							Dict:
        _UpperCamelCase       :    Dict					  =					sorted(['pos', 'neg']					)

 def    __snake_case   (     self    :						Optional[int]					)	->							Optional[int]:
        _UpperCamelCase       :    Union[str, Any]					  =					AudioClassification(audio_column='input_audio'    ,     label_column='input_label'					)
        self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}    ,     task.column_mapping					)

 def    __snake_case   (     self    :						Tuple					)	->							Dict:
        _UpperCamelCase       :    List[str]					  =					Features({'audio': Audio()}					)
        _UpperCamelCase       :    Union[str, Any]					  =					Features({'labels': ClassLabel}					)
        _UpperCamelCase       :    Union[str, Any]					  =					{
            '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    __snake_case   (     self    :						Any					)	->							List[Any]:
        _UpperCamelCase       :    Any					  =					AudioClassification(audio_column='input_audio'    ,     label_column='input_label'					)
        self.assertEqual(task.label_schema['labels']    ,     lowerCamelCase					)
        _UpperCamelCase       :    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 				__lowerCAmelCase					(    a_  ):



 '''simple docstring'''

 def    __snake_case   (     self    :						int					)	->							str:
        _UpperCamelCase       :    Tuple					  =					sorted(['pos', 'neg']					)

 def    __snake_case   (     self    :						Optional[Any]					)	->							Any:
        _UpperCamelCase       :    str					  =					ImageClassification(image_column='input_image'    ,     label_column='input_label'					)
        self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}    ,     task.column_mapping					)

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

 def    __snake_case   (     self    :						List[str]					)	->							Union[str, Any]:
        _UpperCamelCase       :    Any					  =					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					(    a_  ):



 '''simple docstring'''

 def    __snake_case   (     self    :						List[str]					)	->							Dict:
        _UpperCamelCase       :    List[str]					  =					DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
        _UpperCamelCase       :    Tuple					  =					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    :						Dict					):
               return x

        def dont_keep_task(lowerCamelCase    :						List[Any]					):
               _UpperCamelCase       :    Union[str, Any]					  =					deepcopy(lowerCamelCase					)
               _UpperCamelCase       :    List[str]					  =					0
               return out

        _UpperCamelCase       :    Any					  =					dataset.map(lowerCamelCase					)
        assert mapped_dataset.info.task_templates == dataset.info.task_templates
        # reload from cache
        _UpperCamelCase       :    Any					  =					dataset.map(lowerCamelCase					)
        assert mapped_dataset.info.task_templates == dataset.info.task_templates

        _UpperCamelCase       :    int					  =					dataset.map(lowerCamelCase					)
        assert mapped_dataset.info.task_templates == []
        # reload from cache
        _UpperCamelCase       :    int					  =					dataset.map(lowerCamelCase					)
        assert mapped_dataset.info.task_templates == []

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

        def process(lowerCamelCase    :						Any					):
               return example

        _UpperCamelCase       :    Dict					  =					dataset.remove_columns('label'					)
        _UpperCamelCase       :    Union[str, Any]					  =					modified_dataset.map(lowerCamelCase					)
        assert mapped_dataset.info.task_templates == []



