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


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    lowerCamelCase__  (   unittest.TestCase     ):



   def __init__(    self					,      lowerCAmelCase__					,      lowerCAmelCase__=7					,      lowerCAmelCase__=3					,      lowerCAmelCase__=18					,      lowerCAmelCase__=30					,      lowerCAmelCase__=400					,      lowerCAmelCase__=True					,      lowerCAmelCase__=1 / 255					,      lowerCAmelCase__=True					,      lowerCAmelCase__=8					,      )				->     Union[str, Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[int]       =parent
        _UpperCamelCase  :Tuple       =batch_size
        _UpperCamelCase  :Optional[Any]       =num_channels
        _UpperCamelCase  :List[Any]       =image_size
        _UpperCamelCase  :Optional[int]       =min_resolution
        _UpperCamelCase  :Optional[int]       =max_resolution
        _UpperCamelCase  :List[Any]       =do_rescale
        _UpperCamelCase  :Union[str, Any]       =rescale_factor
        _UpperCamelCase  :Any       =do_pad
        _UpperCamelCase  :Any       =pad_size



   def  _UpperCamelCase		(    self     )				->     List[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  _UpperCamelCase		(    self					,      lowerCAmelCase__=False					,      lowerCAmelCase__=False					,      lowerCAmelCase__=False     )				->     Optional[Any]:
        """simple docstring"""





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

        if equal_resolution:
             _UpperCamelCase  :Tuple       =[]
             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  :List[str]       =[]
             for i in range(self.batch_size     ):
                  _UpperCamelCase       ,      _UpperCamelCase  :List[Any]       =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  :List[str]       =[Image.fromarray(np.moveaxis(lowerCAmelCase__					,      0					,      -1     )     ) for x in image_inputs]

        if torchify:
             _UpperCamelCase  :Dict       =[torch.from_numpy(lowerCAmelCase__     ) for x in image_inputs]

        return image_inputs




@require_torch
@require_vision
class    lowerCamelCase__  (   __snake_case       ,				unittest.TestCase     ):
   __UpperCAmelCase           =						SwinaSRImageProcessor if is_vision_available() else None



   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[int]       =SwinaSRImageProcessingTester(self     )



   @property
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        return self.image_processor_tester.prepare_image_processor_dict()



   def  _UpperCamelCase		(    self     )				->     str:
        """simple docstring"""





        _UpperCamelCase  :Union[str, Any]       =self.image_processing_class(**self.image_processor_dict     )
        self.assertTrue(hasattr(lowerCAmelCase__					,      """do_rescale"""     )     )
        self.assertTrue(hasattr(lowerCAmelCase__					,      """rescale_factor"""     )     )
        self.assertTrue(hasattr(lowerCAmelCase__					,      """do_pad"""     )     )
        self.assertTrue(hasattr(lowerCAmelCase__					,      """pad_size"""     )     )



   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        pass



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__     )				->     str:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Union[str, Any]       =get_image_size(lowerCAmelCase__     )
        _UpperCamelCase  :Tuple       =self.image_processor_tester.pad_size

        _UpperCamelCase  :List[Any]       =(old_height // size + 1) * size - old_height
        _UpperCamelCase  :List[Any]       =(old_width // size + 1) * size - old_width
        return old_height + pad_height, old_width + pad_width



   def  _UpperCamelCase		(    self     )				->     Union[str, Any]:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       =self.image_processing_class(**self.image_processor_dict     )
        # create random PIL images
        _UpperCamelCase  :str       =self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__     )
        for image in image_inputs:
             self.assertIsInstance(lowerCAmelCase__					,      Image.Image     )

        # Test not batched input
        _UpperCamelCase  :Tuple       =image_processor(image_inputs[0]					,      return_tensors="""pt"""     ).pixel_values
        _UpperCamelCase       ,      _UpperCamelCase  :str       =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  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase  :Union[str, Any]       =self.image_processing_class(**self.image_processor_dict     )
        # create random numpy tensors
        _UpperCamelCase  :Any       =self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__					,      numpify=lowerCAmelCase__     )
        for image in image_inputs:
             self.assertIsInstance(lowerCAmelCase__					,      np.ndarray     )

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




   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        _UpperCamelCase  :int       =self.image_processing_class(**self.image_processor_dict     )
        # create random PyTorch tensors
        _UpperCamelCase  :List[str]       =self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__					,      torchify=lowerCAmelCase__     )
        for image in image_inputs:
             self.assertIsInstance(lowerCAmelCase__					,      torch.Tensor     )

        # Test not batched input
        _UpperCamelCase  :Optional[int]       =image_processor(image_inputs[0]					,      return_tensors="""pt"""     ).pixel_values
        _UpperCamelCase       ,      _UpperCamelCase  :Optional[int]       =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 copy
import inspect

from transformers.testing_utils import require_torch, torch_device
from transformers.utils.backbone_utils import BackboneType




@require_torch
class    lowerCamelCase__  :
   __UpperCAmelCase           =						()
   __UpperCAmelCase           =						True



   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        _UpperCamelCase  :List[str]       =self.config_class

        # test default config
        _UpperCamelCase  :List[Any]       =config_class()
        self.assertIsNotNone(lowerCAmelCase__     )
        _UpperCamelCase  :List[str]       =["""stem"""] + [f'''stage{idx}''' for idx in range(1					,      len(config.depths     ) + 1     )]
        self.assertEqual(config.stage_names					,      lowerCAmelCase__     )
        self.assertTrue(set(config.out_features     ).issubset(set(config.stage_names     )     )     )

        # Test out_features and out_indices are correctly set
        # out_features and out_indices both None
        _UpperCamelCase  :Any       =config_class(out_features=lowerCAmelCase__					,      out_indices=lowerCAmelCase__     )
        self.assertEqual(config.out_features					,      [config.stage_names[-1]]     )
        self.assertEqual(config.out_indices					,      [len(config.stage_names     ) - 1]     )

        # out_features and out_indices both set
        _UpperCamelCase  :int       =config_class(out_features=["""stem""", """stage1"""]					,      out_indices=[0, 1]     )
        self.assertEqual(config.out_features					,      ["""stem""", """stage1"""]     )
        self.assertEqual(config.out_indices					,      [0, 1]     )

        # Only out_features set
        _UpperCamelCase  :Dict       =config_class(out_features=["""stage1""", """stage3"""]     )
        self.assertEqual(config.out_features					,      ["""stage1""", """stage3"""]     )
        self.assertEqual(config.out_indices					,      [1, 3]     )

        # Only out_indices set
        _UpperCamelCase  :Tuple       =config_class(out_indices=[0, 2]     )
        self.assertEqual(config.out_features					,      [config.stage_names[0], config.stage_names[2]]     )
        self.assertEqual(config.out_indices					,      [0, 2]     )

        # Error raised when out_indices do not correspond to out_features
        with self.assertRaises(lowerCAmelCase__     ):
             _UpperCamelCase  :List[Any]       =config_class(out_features=["""stage1""", """stage2"""]					,      out_indices=[0, 2]     )



   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Optional[Any]       =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             _UpperCamelCase  :Union[str, Any]       =model_class(lowerCAmelCase__     )
             _UpperCamelCase  :Union[str, Any]       =inspect.signature(model.forward     )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             _UpperCamelCase  :Tuple       =[*signature.parameters.keys()]
             _UpperCamelCase  :Any       =["""pixel_values"""]
             self.assertListEqual(arg_names[:1]					,      lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     int:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :List[str]       =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             _UpperCamelCase  :int       =model_class(lowerCAmelCase__     )
             self.assertEqual(len(model.channels     )					,      len(config.out_features     )     )
             _UpperCamelCase  :List[str]       =model.num_features
             _UpperCamelCase  :int       =[config.stage_names.index(lowerCAmelCase__     ) for feat in config.out_features]
             _UpperCamelCase  :List[str]       =[num_features[idx] for idx in out_indices]
             self.assertListEqual(model.channels					,      lowerCAmelCase__     )

             _UpperCamelCase  :Any       =copy.deepcopy(lowerCAmelCase__     )
             _UpperCamelCase  :List[Any]       =None
             _UpperCamelCase  :Optional[Any]       =model_class(lowerCAmelCase__     )
             self.assertEqual(len(model.channels     )					,      1     )
             self.assertListEqual(model.channels					,      [num_features[-1]]     )

             _UpperCamelCase  :Tuple       =copy.deepcopy(lowerCAmelCase__     )
             _UpperCamelCase  :int       =None
             _UpperCamelCase  :int       =model_class(lowerCAmelCase__     )
             self.assertEqual(len(model.channels     )					,      1     )
             self.assertListEqual(model.channels					,      [num_features[-1]]     )



   def  _UpperCamelCase		(    self     )				->     str:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Any       =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             _UpperCamelCase  :List[Any]       =model_class(lowerCAmelCase__     )
             model.to(lowerCAmelCase__     )
             model.eval()
             _UpperCamelCase  :str       =model(**lowerCAmelCase__     )

             self.assertEqual(len(result.feature_maps     )					,      len(config.out_features     )     )
             self.assertEqual(len(model.channels     )					,      len(config.out_features     )     )
             self.assertEqual(len(result.feature_maps     )					,      len(config.out_indices     )     )
             self.assertEqual(len(model.channels     )					,      len(config.out_indices     )     )

             # Check output of last stage is taken if out_features=None, out_indices=None
             _UpperCamelCase  :Any       =copy.deepcopy(lowerCAmelCase__     )
             _UpperCamelCase  :List[Any]       =None
             _UpperCamelCase  :Dict       =model_class(lowerCAmelCase__     )
             model.to(lowerCAmelCase__     )
             model.eval()
             _UpperCamelCase  :str       =model(**lowerCAmelCase__     )

             self.assertEqual(len(result.feature_maps     )					,      1     )
             self.assertEqual(len(model.channels     )					,      1     )

             _UpperCamelCase  :str       =copy.deepcopy(lowerCAmelCase__     )
             _UpperCamelCase  :Dict       =None
             _UpperCamelCase  :Tuple       =model_class(lowerCAmelCase__     )
             model.to(lowerCAmelCase__     )
             model.eval()
             _UpperCamelCase  :Dict       =model(**lowerCAmelCase__     )

             self.assertEqual(len(result.feature_maps     )					,      1     )
             self.assertEqual(len(model.channels     )					,      1     )

             # Check backbone can be initialized with fresh weights
             _UpperCamelCase  :Any       =copy.deepcopy(lowerCAmelCase__     )
             _UpperCamelCase  :Optional[int]       =False
             _UpperCamelCase  :Any       =model_class(lowerCAmelCase__     )
             model.to(lowerCAmelCase__     )
             model.eval()
             _UpperCamelCase  :Optional[int]       =model(**lowerCAmelCase__     )



   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :Dict       =self.model_tester.prepare_config_and_inputs_for_common()

        for backbone_class in self.all_model_classes:
             _UpperCamelCase  :Optional[int]       =backbone_class(lowerCAmelCase__     )

             self.assertTrue(hasattr(lowerCAmelCase__					,      """backbone_type"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """stage_names"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """num_features"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """out_indices"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """out_features"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """out_feature_channels"""     )     )
             self.assertTrue(hasattr(lowerCAmelCase__					,      """channels"""     )     )

             self.assertIsInstance(backbone.backbone_type					,      lowerCAmelCase__     )
             # Verify num_features has been initialized in the backbone init
             self.assertIsNotNone(backbone.num_features     )
             self.assertTrue(len(backbone.channels     ) == len(backbone.out_indices     )     )
             self.assertTrue(len(backbone.stage_names     ) == len(backbone.num_features     )     )
             self.assertTrue(len(backbone.channels     ) <= len(backbone.num_features     )     )
             self.assertTrue(len(backbone.out_feature_channels     ) == len(backbone.stage_names     )     )




   def  _UpperCamelCase		(    self     )				->     Tuple:
        """simple docstring"""





        _UpperCamelCase       ,      _UpperCamelCase  :List[Any]       =self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase  :Union[str, Any]       =inputs_dict["""pixel_values"""].shape[0]

        for backbone_class in self.all_model_classes:
             _UpperCamelCase  :str       =backbone_class(lowerCAmelCase__     )
             backbone.to(lowerCAmelCase__     )
             backbone.eval()

             _UpperCamelCase  :Any       =backbone(**lowerCAmelCase__     )

             # Test default outputs and verify feature maps
             self.assertIsInstance(outputs.feature_maps					,      lowerCAmelCase__     )
             self.assertTrue(len(outputs.feature_maps     ) == len(backbone.channels     )     )
             for feature_map, n_channels in zip(outputs.feature_maps					,      backbone.channels     ):
                  self.assertTrue(feature_map.shape[:2]					,      (batch_size, n_channels)     )
             self.assertIsNone(outputs.hidden_states     )
             self.assertIsNone(outputs.attentions     )

             # Test output_hidden_states=True
             _UpperCamelCase  :Any       =backbone(**lowerCAmelCase__					,      output_hidden_states=lowerCAmelCase__     )
             self.assertIsNotNone(outputs.hidden_states     )
             self.assertTrue(len(outputs.hidden_states     )					,      len(backbone.stage_names     )     )
             for hidden_state, n_channels in zip(outputs.hidden_states					,      backbone.channels     ):
                  self.assertTrue(hidden_state.shape[:2]					,      (batch_size, n_channels)     )

             # Test output_attentions=True
             if self.has_attentions:
                  _UpperCamelCase  :int       =backbone(**lowerCAmelCase__					,      output_attentions=lowerCAmelCase__     )
                  self.assertIsNotNone(outputs.attentions     )