





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 SwinaSRImageProcessor
     from transformers.image_transforms import get_image_size



class 				_UpperCamelCase       (						unittest.TestCase  ):

       def __init__(		self:			List[Any]       , _SCREAMING_SNAKE_CASE:			Tuple       , _SCREAMING_SNAKE_CASE:			Optional[Any]=7       , _SCREAMING_SNAKE_CASE:			Any=3       , _SCREAMING_SNAKE_CASE:			List[Any]=18       , _SCREAMING_SNAKE_CASE:			Tuple=30       , _SCREAMING_SNAKE_CASE:			List[str]=400       , _SCREAMING_SNAKE_CASE:			Tuple=True       , _SCREAMING_SNAKE_CASE:			List[str]=1 / 255       , _SCREAMING_SNAKE_CASE:			List[Any]=True       , _SCREAMING_SNAKE_CASE:			Tuple=8       , )							->			Optional[int]:




              """simple docstring"""


              UpperCamelCase_ 							=	parent
              UpperCamelCase_ 							=	batch_size
              UpperCamelCase_ 							=	num_channels
              UpperCamelCase_ 							=	image_size
              UpperCamelCase_ 							=	min_resolution
              UpperCamelCase_ 							=	max_resolution
              UpperCamelCase_ 							=	do_rescale
              UpperCamelCase_ 							=	rescale_factor
              UpperCamelCase_ 							=	do_pad
              UpperCamelCase_ 							=	pad_size

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              return {
                  "do_rescale": self.do_rescale,
                  "rescale_factor": self.rescale_factor,
                  "do_pad": self.do_pad,
                  "pad_size": self.pad_size,
              }



       def lowercase			(		self:			Tuple       , _SCREAMING_SNAKE_CASE:			List[Any]=False       , _SCREAMING_SNAKE_CASE:			List[str]=False       , _SCREAMING_SNAKE_CASE:			Any=False		)							->			List[str]:




              """simple docstring"""


              assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

              if equal_resolution:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            image_inputs.append(
                                np.random.randint(
                                    255       , size=(self.num_channels, self.max_resolution, self.max_resolution)       , dtype=np.uinta		)		)
              else:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            UpperCamelCase_							,			UpperCamelCase_ 							=	np.random.choice(np.arange(self.min_resolution       , self.max_resolution		)       , 2		)
                            image_inputs.append(np.random.randint(255       , size=(self.num_channels, width, height)       , dtype=np.uinta		)		)

              if not numpify and not torchify:
                     # PIL expects the channel dimension as last dimension
                     UpperCamelCase_ 							=	[Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE       , 0       , -1		)		) for x in image_inputs]

              if torchify:
                     UpperCamelCase_ 							=	[torch.from_numpy(_SCREAMING_SNAKE_CASE		) for x in image_inputs]

              return image_inputs



@require_torch
@require_vision
class 				_UpperCamelCase       (						lowerCAmelCase_	,    unittest.TestCase  ):
       _UpperCamelCase					:       Union[str, Any]       = SwinaSRImageProcessor if is_vision_available() else None

       def lowercase			(		self:			Union[str, Any]		)							->			str:




              """simple docstring"""


              UpperCamelCase_ 							=	SwinaSRImageProcessingTester(self		)

       @property
       def lowercase			(		self:			Optional[int]		)							->			Optional[int]:




              """simple docstring"""


              return self.image_processor_tester.prepare_image_processor_dict()

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_rescale"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "rescale_factor"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_pad"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "pad_size"		)		)

       def lowercase			(		self:			List[Any]		)							->			Tuple:




              """simple docstring"""


              pass

       def lowercase			(		self:			int       , _SCREAMING_SNAKE_CASE:			Optional[Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_							,			UpperCamelCase_ 							=	get_image_size(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_ 							=	self.image_processor_tester.pad_size

              UpperCamelCase_ 							=	(old_height // size + 1) * size - old_height
              UpperCamelCase_ 							=	(old_width // size + 1) * size - old_width
              return old_height + pad_height, old_width + pad_width

       def lowercase			(		self:			Dict		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random PIL images
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(equal_resolution=_SCREAMING_SNAKE_CASE		)
              for image in image_inputs:
                     self.assertIsInstance(_SCREAMING_SNAKE_CASE       , Image.Image		)

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(np.array(image_inputs[0]		)		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )

       def lowercase			(		self:			Any		)							->			Any:




              """simple docstring"""


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

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )



       def lowercase			(		self:			str		)							->			Optional[int]:




              """simple docstring"""


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

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )






"""simple docstring"""







import inspect

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
     import jax







@require_flax
class  UpperCamelCase__  :




      """simple docstring"""




      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[int]			):
        lowerCAmelCase_		,lowerCAmelCase_  :							Any								=					self.prepare_init_args_and_inputs_for_common()

        lowerCAmelCase_  :							List[str]								=					self.model_class(**SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Any								=					model.init(inputs_dict['prng_key']       ,     inputs_dict['sample']			)
        jax.lax.stop_gradient(SCREAMING_SNAKE_CASE_			)

        lowerCAmelCase_  :							Tuple								=					model.apply(SCREAMING_SNAKE_CASE_       ,     inputs_dict['sample']			)

        if isinstance(SCREAMING_SNAKE_CASE_       ,     SCREAMING_SNAKE_CASE_			):
          lowerCAmelCase_  :							str								=					output.sample

        self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Any								=					inputs_dict['sample'].shape
        self.assertEqual(output.shape       ,     SCREAMING_SNAKE_CASE_       ,     'Input and output shapes do not match'			)



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        lowerCAmelCase_		,lowerCAmelCase_  :							Union[str, Any]								=					self.prepare_init_args_and_inputs_for_common()

        lowerCAmelCase_  :							Tuple								=					1_6
        lowerCAmelCase_  :							Dict								=					(1_6, 3_2)

        lowerCAmelCase_  :							Any								=					self.model_class(**SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Optional[Any]								=					model.init(inputs_dict['prng_key']       ,     inputs_dict['sample']			)
        jax.lax.stop_gradient(SCREAMING_SNAKE_CASE_			)

        lowerCAmelCase_  :							Optional[Any]								=					model.apply(SCREAMING_SNAKE_CASE_       ,     inputs_dict['sample']			)

        if isinstance(SCREAMING_SNAKE_CASE_       ,     SCREAMING_SNAKE_CASE_			):
          lowerCAmelCase_  :							Dict								=					output.sample

        self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)
        lowerCAmelCase_  :							Optional[Any]								=					inputs_dict['sample'].shape
        self.assertEqual(output.shape       ,     SCREAMING_SNAKE_CASE_       ,     'Input and output shapes do not match'			)





      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]			):
        lowerCAmelCase_  :							List[str]								=					'kwargs' in inspect.signature(self.model_class.__init__			).parameters
        lowerCAmelCase_  :							Optional[Any]								=					len(self.model_class._deprecated_kwargs			) > 0

        if has_kwarg_in_model_class and not has_deprecated_kwarg:
          raise ValueError(
              F"{self.model_class} has `**kwargs` in its __init__ method but has not defined any deprecated kwargs"
              ' under the `_deprecated_kwargs` class attribute. Make sure to either remove `**kwargs` if there are'
              ' no deprecated arguments or add the deprecated argument with `_deprecated_kwargs ='
              ' [<deprecated_argument>]`'			)

        if not has_kwarg_in_model_class and has_deprecated_kwarg:
          raise ValueError(
              F"{self.model_class} doesn't have `**kwargs` in its __init__ method but has defined deprecated kwargs"
              ' under the `_deprecated_kwargs` class attribute. Make sure to either add the `**kwargs` argument to'
              F" {self.model_class}.__init__ if there are deprecated arguments or remove the deprecated argument"
              ' from `_deprecated_kwargs = [<deprecated_argument>]`'			)





