import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

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


if is_flax_available():
 import jax
 import jax.numpy as jnp

 from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class    __lowerCAmelCase  (       unittest.TestCase						):



 '''simple docstring'''

 def __init__(			self       :		Tuple       ,			lowerCamelCase       :		List[str]       ,			lowerCamelCase       :		List[str]=3       ,			lowerCamelCase       :		Optional[int]=3_2       ,			lowerCamelCase       :		List[str]=3       ,			lowerCamelCase       :		List[Any]=1_0       ,			lowerCamelCase       :		Any=[1_0, 2_0, 3_0, 4_0]       ,			lowerCamelCase       :		List[Any]=[1, 1, 2, 1]       ,			lowerCamelCase       :		List[str]=True       ,			lowerCamelCase       :		List[Any]=True       ,			lowerCamelCase       :		Optional[int]="relu"       ,			lowerCamelCase       :		Tuple=3       ,			lowerCamelCase       :		Optional[int]=None       ,			) ->							List[Any]:
        _UpperCamelCase     :       Optional[int]  						=  parent
        _UpperCamelCase     :       List[str]  						=  batch_size
        _UpperCamelCase     :       Optional[Any]  						=  image_size
        _UpperCamelCase     :       Optional[int]  						=  num_channels
        _UpperCamelCase     :       Optional[int]  						=  embeddings_size
        _UpperCamelCase     :       Any  						=  hidden_sizes
        _UpperCamelCase     :       Optional[int]  						=  depths
        _UpperCamelCase     :       int  						=  is_training
        _UpperCamelCase     :       List[Any]  						=  use_labels
        _UpperCamelCase     :       List[str]  						=  hidden_act
        _UpperCamelCase     :       Any  						=  num_labels
        _UpperCamelCase     :       Dict  						=  scope
        _UpperCamelCase     :       Optional[int]  						=  len(lowerCamelCase  )

 def 					__snake_case					(			self       :		Union[str, Any]  ) ->							Any:
        _UpperCamelCase     :       Tuple  						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        _UpperCamelCase     :       Optional[Any]  						=  self.get_config()

        return config, pixel_values

 def 					__snake_case					(			self       :		Any  ) ->							Dict:
        return ResNetConfig(
            num_channels=self.num_channels       ,			embeddings_size=self.embeddings_size       ,			hidden_sizes=self.hidden_sizes       ,			depths=self.depths       ,			hidden_act=self.hidden_act       ,			num_labels=self.num_labels       ,			image_size=self.image_size       ,			)

 def 					__snake_case					(			self       :		int       ,			lowerCamelCase       :		Optional[Any]       ,			lowerCamelCase       :		Optional[Any]  ) ->							Tuple:
        _UpperCamelCase     :       Union[str, Any]  						=  FlaxResNetModel(config=lowerCamelCase  )
        _UpperCamelCase     :       Optional[int]  						=  model(lowerCamelCase  )

        # Output shape (b, c, h, w)
        self.parent.assertEqual(
            result.last_hidden_state.shape       ,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)       ,			)

 def 					__snake_case					(			self       :		Tuple       ,			lowerCamelCase       :		Tuple       ,			lowerCamelCase       :		Optional[int]  ) ->							Optional[Any]:
        _UpperCamelCase     :       List[Any]  						=  self.num_labels
        _UpperCamelCase     :       List[str]  						=  FlaxResNetForImageClassification(config=lowerCamelCase  )
        _UpperCamelCase     :       Dict  						=  model(lowerCamelCase  )
        self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_labels)  )

 def 					__snake_case					(			self       :		int  ) ->							List[str]:
        _UpperCamelCase     :       Tuple  						=  self.prepare_config_and_inputs()
        _UpperCamelCase						,      _UpperCamelCase     :       Optional[Any]  						=  config_and_inputs
        _UpperCamelCase     :       int  						=  {'pixel_values': pixel_values}
        return config, inputs_dict







@require_flax
class    __lowerCAmelCase  (       a_,	unittest.TestCase						):



 '''simple docstring'''
 _lowerCamelCase						:	Optional[Any]				    = (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

 _lowerCamelCase						:	List[Any]				    = False
 _lowerCamelCase						:	str				    = False
 _lowerCamelCase						:	str				    = False

 def 					__snake_case					(			self       :		Optional[int]  ) ->							None:
        _UpperCamelCase     :       Dict  						=  FlaxResNetModelTester(self  )
        _UpperCamelCase     :       List[Any]  						=  ConfigTester(self       ,			config_class=lowerCamelCase       ,			has_text_modality=lowerCamelCase  )

 def 					__snake_case					(			self       :		Optional[Any]  ) ->							Optional[Any]:
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

 def 					__snake_case					(			self       :		Dict  ) ->							List[Any]:
        return

 def 					__snake_case					(			self       :		int  ) ->							str:
        _UpperCamelCase     :       Union[str, Any]  						=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase  )

 def 					__snake_case					(			self       :		Optional[Any]  ) ->							Any:
        _UpperCamelCase     :       Optional[int]  						=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase  )

 @unittest.skip(reason='ResNet does not use inputs_embeds'  )
 def 					__snake_case					(			self       :		Dict  ) ->							str:
        pass

 @unittest.skip(reason='ResNet does not support input and output embeddings'  )
 def 					__snake_case					(			self       :		Union[str, Any]  ) ->							List[Any]:
        pass

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

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

               _UpperCamelCase     :       Dict  						=  ['pixel_values']
               self.assertListEqual(arg_names[:1]       ,			lowerCamelCase  )

 def 					__snake_case					(			self       :		List[Any]  ) ->							Optional[Any]:
        def check_hidden_states_output(lowerCamelCase       :		Dict       ,			lowerCamelCase       :		Union[str, Any]       ,			lowerCamelCase       :		Optional[int]  ):
               _UpperCamelCase     :       Optional[int]  						=  model_class(lowerCamelCase  )

               _UpperCamelCase     :       Optional[Any]  						=  model(**self._prepare_for_class(lowerCamelCase       ,			lowerCamelCase  )  )

               _UpperCamelCase     :       Tuple  						=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               _UpperCamelCase     :       str  						=  self.model_tester.num_stages
               self.assertEqual(len(lowerCamelCase  )       ,			expected_num_stages + 1  )

 @unittest.skip(reason='ResNet does not use feedforward chunking'  )
 def 					__snake_case					(			self       :		int  ) ->							int:
        pass

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

        for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__  ):
                      _UpperCamelCase     :       Any  						=  self._prepare_for_class(lowerCamelCase       ,			lowerCamelCase  )
                      _UpperCamelCase     :       List[str]  						=  model_class(lowerCamelCase  )

                      @jax.jit
                      def model_jitted(lowerCamelCase       :		int       ,			**lowerCamelCase       :		str  ):
                             return model(pixel_values=lowerCamelCase       ,			**lowerCamelCase  )

                      with self.subTest('JIT Enabled'  ):
                             _UpperCamelCase     :       Dict  						=  model_jitted(**lowerCamelCase  ).to_tuple()

                      with self.subTest('JIT Disabled'  ):
                             with jax.disable_jit():
                                    _UpperCamelCase     :       Optional[int]  						=  model_jitted(**lowerCamelCase  ).to_tuple()

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







def SCREAMING_SNAKE_CASE				(     ):
       _UpperCamelCase     :       Any  						=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





@require_flax
class    __lowerCAmelCase  (       unittest.TestCase						):



 '''simple docstring'''

 @cached_property
 def 					__snake_case					(			self       :		int  ) ->							List[str]:
        return AutoImageProcessor.from_pretrained('microsoft/resnet-50'  ) if is_vision_available() else None

 @slow
 def 					__snake_case					(			self       :		Any  ) ->							List[Any]:
        _UpperCamelCase     :       Optional[Any]  						=  FlaxResNetForImageClassification.from_pretrained('microsoft/resnet-50'  )

        _UpperCamelCase     :       str  						=  self.default_image_processor
        _UpperCamelCase     :       List[str]  						=  prepare_img()
        _UpperCamelCase     :       Optional[Any]  						=  image_processor(images=lowerCamelCase       ,			return_tensors='np'  )

        _UpperCamelCase     :       str  						=  model(**lowerCamelCase  )

        # verify the logits
        _UpperCamelCase     :       Optional[int]  						=  (1, 1_0_0_0)
        self.assertEqual(outputs.logits.shape       ,			lowerCamelCase  )

        _UpperCamelCase     :       Dict  						=  jnp.array([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]  )

        self.assertTrue(jnp.allclose(outputs.logits[0, :3]       ,			lowerCamelCase       ,			atol=1e-4  )  )




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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import TvltImageProcessor


def SCREAMING_SNAKE_CASE				(     lowercase_:	Tuple		,						lowercase_:	Optional[int]=10		,						lowercase_:	Optional[Any]=10		,						lowercase_:	Optional[Any]=False		,						lowercase_:	Any=False				):
       _UpperCamelCase     :       List[Any]  						=  []
       for i in range(image_processor_tester.num_frames				):
              video.append(np.random.randint(255		,						size=(image_processor_tester.num_channels, width, height)		,						dtype=np.uinta				)				)

       if not numpify and not torchify:
              # PIL expects the channel dimension as last dimension
              _UpperCamelCase     :       Tuple  						=  [Image.fromarray(np.moveaxis(lowercase_		,						0		,						-1				)				) for frame in video]

       if torchify:
              _UpperCamelCase     :       Union[str, Any]  						=  [torch.from_numpy(lowercase_				) for frame in video]

       return video


def SCREAMING_SNAKE_CASE				(     lowercase_:	List[str]		,						lowercase_:	Optional[Any]=False		,						lowercase_:	Tuple=False		,						lowercase_:	Union[str, Any]=False				):
       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

       _UpperCamelCase     :       Any  						=  []
       for i in range(image_processor_tester.batch_size				):
              if equal_resolution:
                     _UpperCamelCase     :       str  						=  image_processor_tester.max_resolution
              else:
                     _UpperCamelCase						,      _UpperCamelCase     :       int  						=  np.random.choice(
                         np.arange(image_processor_tester.min_resolution		,						image_processor_tester.max_resolution				)		,						2				)
                     _UpperCamelCase     :       Optional[Any]  						=  prepare_video(
                         image_processor_tester=lowercase_		,						width=lowercase_		,						height=lowercase_		,						numpify=lowercase_		,						torchify=lowercase_		,						)
              video_inputs.append(lowercase_				)

       return video_inputs




class    __lowerCAmelCase  (       unittest.TestCase						):



 '''simple docstring'''

 def __init__(			self       :		Optional[Any]       ,			lowerCamelCase       :		Union[str, Any]       ,			lowerCamelCase       :		Optional[int]=7       ,			lowerCamelCase       :		List[Any]=3       ,			lowerCamelCase       :		str=4       ,			lowerCamelCase       :		Union[str, Any]=1_8       ,			lowerCamelCase       :		str=3_0       ,			lowerCamelCase       :		List[str]=4_0_0       ,			lowerCamelCase       :		Tuple=True       ,			lowerCamelCase       :		Union[str, Any]=None       ,			lowerCamelCase       :		List[str]=True       ,			lowerCamelCase       :		Optional[Any]=[0.5, 0.5, 0.5]       ,			lowerCamelCase       :		Any=[0.5, 0.5, 0.5]       ,			lowerCamelCase       :		str=True       ,			lowerCamelCase       :		Optional[Any]=None       ,			) ->							Union[str, Any]:
        _UpperCamelCase     :       Optional[int]  						=  size if size is not None else {'shortest_edge': 1_8}
        _UpperCamelCase     :       Dict  						=  crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}

        _UpperCamelCase     :       Any  						=  parent
        _UpperCamelCase     :       Optional[Any]  						=  batch_size
        _UpperCamelCase     :       List[Any]  						=  num_channels
        _UpperCamelCase     :       List[Any]  						=  num_frames
        _UpperCamelCase     :       Union[str, Any]  						=  image_size
        _UpperCamelCase     :       Dict  						=  min_resolution
        _UpperCamelCase     :       int  						=  max_resolution
        _UpperCamelCase     :       Union[str, Any]  						=  do_resize
        _UpperCamelCase     :       str  						=  size
        _UpperCamelCase     :       Dict  						=  do_normalize
        _UpperCamelCase     :       Union[str, Any]  						=  image_mean
        _UpperCamelCase     :       Optional[int]  						=  image_std
        _UpperCamelCase     :       Tuple  						=  do_center_crop
        _UpperCamelCase     :       Any  						=  crop_size

 def 					__snake_case					(			self       :		Tuple  ) ->							Optional[Any]:
        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "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    __lowerCAmelCase  (       a_,	unittest.TestCase						):



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

 def 					__snake_case					(			self       :		int  ) ->							Optional[int]:
        _UpperCamelCase     :       Optional[Any]  						=  TvltImageProcessorTester(self  )

 @property
 def 					__snake_case					(			self       :		Optional[Any]  ) ->							Any:
        return self.image_processor_tester.prepare_image_processor_dict()

 def 					__snake_case					(			self       :		Union[str, Any]  ) ->							str:
        _UpperCamelCase     :       Tuple  						=  self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'image_mean'  )  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'image_std'  )  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'do_normalize'  )  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'do_resize'  )  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'do_center_crop'  )  )
        self.assertTrue(hasattr(lowerCamelCase       ,			'size'  )  )

 def 					__snake_case					(			self       :		Dict  ) ->							Optional[int]:
        # Initialize image_processor
        _UpperCamelCase     :       str  						=  self.image_processing_class(**self.image_processor_dict  )
        # create random PIL videos
        _UpperCamelCase     :       int  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase  )
        for video in video_inputs:
               self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
               self.assertIsInstance(video[0]       ,			Image.Image  )

        # Test not batched input
        _UpperCamelCase     :       Dict  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)

        # Test batched
        _UpperCamelCase     :       Any  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)

 def 					__snake_case					(			self       :		Union[str, Any]  ) ->							List[str]:
        # Initialize image_processor
        _UpperCamelCase     :       Optional[int]  						=  self.image_processing_class(**self.image_processor_dict  )
        # create random numpy tensors
        _UpperCamelCase     :       int  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase       ,			numpify=lowerCamelCase  )
        for video in video_inputs:
               self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
               self.assertIsInstance(video[0]       ,			np.ndarray  )

        # Test not batched input
        _UpperCamelCase     :       Optional[int]  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)

        # Test batched
        _UpperCamelCase     :       int  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)

 def 					__snake_case					(			self       :		Optional[Any]  ) ->							Any:
        # Initialize image_processor
        _UpperCamelCase     :       int  						=  self.image_processing_class(**self.image_processor_dict  )
        # create random PyTorch tensors
        _UpperCamelCase     :       Optional[Any]  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase       ,			torchify=lowerCamelCase  )
        for video in video_inputs:
               self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
               self.assertIsInstance(video[0]       ,			torch.Tensor  )

        # Test not batched input
        _UpperCamelCase     :       Dict  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)

        # Test batched
        _UpperCamelCase     :       Optional[int]  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
        self.assertEqual(
            encoded_videos.shape       ,			(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            )       ,			)



