






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 LevitImageProcessor





class __lowerCamelCase (      unittest.TestCase):





	"""simple docstring"""






	def __init__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase=7       ,    UpperCAmelCase=3       ,    UpperCAmelCase=18       ,    UpperCAmelCase=30       ,    UpperCAmelCase=400       ,    UpperCAmelCase=True       ,    UpperCAmelCase=None       ,    UpperCAmelCase=True       ,    UpperCAmelCase=None       ,    UpperCAmelCase=True       ,    UpperCAmelCase=[0.5, 0.5, 0.5]       ,    UpperCAmelCase=[0.5, 0.5, 0.5]       ,    ):
							"""simple docstring"""







							_UpperCAmelCase									=			size if size is not None else {'shortest_edge': 18}
							_UpperCAmelCase									=			crop_size if crop_size is not None else {'height': 18, 'width': 18}
							_UpperCAmelCase									=			parent
							_UpperCAmelCase									=			batch_size
							_UpperCAmelCase									=			num_channels
							_UpperCAmelCase									=			image_size
							_UpperCAmelCase									=			min_resolution
							_UpperCAmelCase									=			max_resolution
							_UpperCAmelCase									=			do_resize
							_UpperCAmelCase									=			size
							_UpperCAmelCase									=			do_center_crop
							_UpperCAmelCase									=			crop_size
							_UpperCAmelCase									=			do_normalize
							_UpperCAmelCase									=			image_mean
							_UpperCAmelCase									=			image_std

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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





@require_torch
@require_vision
class __lowerCamelCase (      snake_case__     ,       unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=      LevitImageProcessor if is_vision_available() else None

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			LevitImageProcessingTester(self    )

	@property
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return self.image_processor_tester.prepare_image_processor_dict()

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'image_mean'    )    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'image_std'    )    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'do_normalize'    )    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'do_resize'    )    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'do_center_crop'    )    )
							self.assertTrue(hasattr(UpperCAmelCase       ,    'size'    )    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.image_processing_class.from_dict(self.image_processor_dict    )
							self.assertEqual(image_processor.size       ,    {'shortest_edge': 18}    )
							self.assertEqual(image_processor.crop_size       ,    {'height': 18, 'width': 18}    )

							_UpperCAmelCase									=			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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict    )
							# create random PIL images
							_UpperCAmelCase									=			prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=UpperCAmelCase    )
							for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase       ,    Image.Image    )

							# Test not batched input
							_UpperCAmelCase									=			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
							_UpperCAmelCase									=			image_processing(UpperCAmelCase       ,    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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict    )
							# create random numpy tensors
							_UpperCAmelCase									=			prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=UpperCAmelCase       ,    numpify=UpperCAmelCase    )
							for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase       ,    np.ndarray    )

							# Test not batched input
							_UpperCAmelCase									=			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
							_UpperCAmelCase									=			image_processing(UpperCAmelCase       ,    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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.image_processing_class(**self.image_processor_dict    )
							# create random PyTorch tensors
							_UpperCAmelCase									=			prepare_image_inputs(self.image_processor_tester       ,    equal_resolution=UpperCAmelCase       ,    torchify=UpperCAmelCase    )
							for image in image_inputs:
													self.assertIsInstance(UpperCAmelCase       ,    torch.Tensor    )

							# Test not batched input
							_UpperCAmelCase									=			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
							_UpperCAmelCase									=			image_processing(UpperCAmelCase       ,    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'],
							    )       ,    )


"""simple docstring"""





import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
    import jax

    from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel


class A_	(unittest.TestCase      ):




  '''simple docstring'''







  def __init__(		self				,   lowercase_				,   lowercase_=13				,   lowercase_=30				,   lowercase_=2				,   lowercase_=3				,   lowercase_=True				,   lowercase_=True				,   lowercase_=32				,   lowercase_=5				,   lowercase_=4				,   lowercase_=37				,   lowercase_="gelu"				,   lowercase_=0.1				,   lowercase_=0.1				,   lowercase_=10				,   lowercase_=0.02				,   ):

     """simple docstring"""
     UpperCAmelCase_					:					Tuple			     =    parent
     UpperCAmelCase_					:					List[str]			     =    batch_size
     UpperCAmelCase_					:					Union[str, Any]			     =    image_size
     UpperCAmelCase_					:					List[str]			     =    patch_size
     UpperCAmelCase_					:					Union[str, Any]			     =    num_channels
     UpperCAmelCase_					:					Optional[int]			     =    is_training
     UpperCAmelCase_					:					Dict			     =    use_labels
     UpperCAmelCase_					:					Any			     =    hidden_size
     UpperCAmelCase_					:					Optional[Any]			     =    num_hidden_layers
     UpperCAmelCase_					:					Optional[Any]			     =    num_attention_heads
     UpperCAmelCase_					:					Dict			     =    intermediate_size
     UpperCAmelCase_					:					Optional[Any]			     =    hidden_act
     UpperCAmelCase_					:					Optional[Any]			     =    hidden_dropout_prob
     UpperCAmelCase_					:					Tuple			     =    attention_probs_dropout_prob
     UpperCAmelCase_					:					Dict			     =    type_sequence_label_size
     UpperCAmelCase_					:					Optional[Any]			     =    initializer_range

     # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     UpperCAmelCase_					:					Any			     =    (image_size // patch_size) ** 2
     UpperCAmelCase_					:					List[str]			     =    num_patches + 1







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Optional[Any]			     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

     UpperCAmelCase_					:					Dict			     =    ViTConfig(
         image_size=self.image_size				,   patch_size=self.patch_size				,   num_channels=self.num_channels				,   hidden_size=self.hidden_size				,   num_hidden_layers=self.num_hidden_layers				,   num_attention_heads=self.num_attention_heads				,   intermediate_size=self.intermediate_size				,   hidden_act=self.hidden_act				,   hidden_dropout_prob=self.hidden_dropout_prob				,   attention_probs_dropout_prob=self.attention_probs_dropout_prob				,   is_decoder=lowercase_				,   initializer_range=self.initializer_range				,   )

     return config, pixel_values







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[str]			     =    FlaxViTModel(config=lowercase_  )
     UpperCAmelCase_					:					int			     =    model(lowercase_  )
     # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
     UpperCAmelCase_					:					Optional[Any]			     =    (self.image_size, self.image_size)
     UpperCAmelCase_					:					List[Any]			     =    (self.patch_size, self.patch_size)
     UpperCAmelCase_					:					str			     =    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
     self.parent.assertEqual(result.last_hidden_state.shape				,   (self.batch_size, num_patches + 1, self.hidden_size)  )







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     UpperCAmelCase_					:					Tuple			     =    self.type_sequence_label_size
     UpperCAmelCase_					:					Tuple			     =    FlaxViTForImageClassification(config=lowercase_  )
     UpperCAmelCase_					:					str			     =    model(lowercase_  )
     self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.type_sequence_label_size)  )

     # test greyscale images
     UpperCAmelCase_					:					Any			     =    1
     UpperCAmelCase_					:					Optional[int]			     =    FlaxViTForImageClassification(lowercase_  )

     UpperCAmelCase_					:					List[Any]			     =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
     UpperCAmelCase_					:					List[Any]			     =    model(lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    self.prepare_config_and_inputs()
     (
         (
         UpperCAmelCase_
     )     ,   (
         UpperCAmelCase_
     )     ,   
     )					:					Tuple			     =    config_and_inputs
     UpperCAmelCase_					:					Union[str, Any]			     =    {"pixel_values": pixel_values}
     return config, inputs_dict




@require_flax
class A_	(lowercase__				,unittest.TestCase      ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						Any       =		(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    FlaxViTModelTester(self  )
     UpperCAmelCase_					:					Dict			     =    ConfigTester(self				,   config_class=lowercase_				,   has_text_modality=lowercase_				,   hidden_size=37  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     self.config_tester.run_common_tests()







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Optional[Any]			     =    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_     ,   UpperCAmelCase_					:					List[str]			     =    self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCAmelCase_					:					Optional[Any]			     =    model_class(lowercase_  )
        UpperCAmelCase_					:					Optional[int]			     =    inspect.signature(model.__call__  )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCAmelCase_					:					List[str]			     =    [*signature.parameters.keys()]

        UpperCAmelCase_					:					List[str]			     =    ["pixel_values"]
        self.assertListEqual(arg_names[:1]				,   lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_     ,   UpperCAmelCase_					:					Tuple			     =    self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__  ):
           UpperCAmelCase_					:					Union[str, Any]			     =    self._prepare_for_class(lowercase_				,   lowercase_  )
           UpperCAmelCase_					:					Tuple			     =    model_class(lowercase_  )

           @jax.jit
           def model_jitted(lowercase_				,   **lowercase_  ):
              return model(pixel_values=lowercase_				,   **lowercase_  )

           with self.subTest("JIT Enabled"  ):
              UpperCAmelCase_					:					Union[str, Any]			     =    model_jitted(**lowercase_  ).to_tuple()

           with self.subTest("JIT Disabled"  ):
              with jax.disable_jit():
                 UpperCAmelCase_					:					Tuple			     =    model_jitted(**lowercase_  ).to_tuple()

           self.assertEqual(len(lowercase_  )				,   len(lowercase_  )  )
           for jitted_output, output in zip(lowercase_				,   lowercase_  ):
              self.assertEqual(jitted_output.shape				,   output.shape  )







  @slow
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     for model_class_name in self.all_model_classes:
        UpperCAmelCase_					:					Union[str, Any]			     =    model_class_name.from_pretrained("google/vit-base-patch16-224"  )
        UpperCAmelCase_					:					List[str]			     =    model(np.ones((1, 3, 224, 224)  )  )
        self.assertIsNotNone(lowercase_  )


