





import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
       from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor





class A_					:




   def __init__(self	:int    ,   _UpperCamelCase	:int    ,   _UpperCamelCase	:Dict=13    ,   _UpperCamelCase	:int=32    ,   _UpperCamelCase	:Dict=3    ,   _UpperCamelCase	:int=4    ,   _UpperCamelCase	:Optional[Any]=[10, 20, 30, 40]    ,   _UpperCamelCase	:Optional[int]=[2, 2, 3, 2]    ,   _UpperCamelCase	:List[Any]=True    ,   _UpperCamelCase	:List[Any]=True    ,   _UpperCamelCase	:Union[str, Any]=37    ,   _UpperCamelCase	:List[str]="gelu"    ,   _UpperCamelCase	:Optional[Any]=10    ,   _UpperCamelCase	:str=0.0_2    ,   _UpperCamelCase	:List[Any]=["stage2", "stage3", "stage4"]    ,   _UpperCamelCase	:Union[str, Any]=[2, 3, 4]    ,   _UpperCamelCase	:str=None    ,   )->					Optional[Any]:
         __A          =				parent
         __A          =				batch_size
         __A          =				image_size
         __A          =				num_channels
         __A          =				num_stages
         __A          =				hidden_sizes
         __A          =				depths
         __A          =				is_training
         __A          =				use_labels
         __A          =				intermediate_size
         __A          =				hidden_act
         __A          =				num_labels
         __A          =				initializer_range
         __A          =				out_features
         __A          =				out_indices
         __A          =				scope




   def _lowerCAmelCase      (self	:List[str] )->					Optional[int]:
         __A          =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

         __A          =				None
         if self.use_labels:
               __A          =				ids_tensor([self.batch_size]    ,   self.num_labels )

         __A          =				self.get_config()

         return config, pixel_values, labels




   def _lowerCAmelCase      (self	:int )->					List[str]:
         return ConvNextVaConfig(
             num_channels=self.num_channels    ,   hidden_sizes=self.hidden_sizes    ,   depths=self.depths    ,   num_stages=self.num_stages    ,   hidden_act=self.hidden_act    ,   is_decoder=_UpperCamelCase    ,   initializer_range=self.initializer_range    ,   out_features=self.out_features    ,   out_indices=self.out_indices    ,   num_labels=self.num_labels    ,   )




   def _lowerCAmelCase      (self	:Any    ,   _UpperCamelCase	:List[str]    ,   _UpperCamelCase	:List[Any]    ,   _UpperCamelCase	:int )->					Union[str, Any]:
         __A          =				ConvNextVaModel(config=_UpperCamelCase )
         model.to(_UpperCamelCase )
         model.eval()
         __A          =				model(_UpperCamelCase )
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape    ,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,   )




   def _lowerCAmelCase      (self	:List[Any]    ,   _UpperCamelCase	:List[Any]    ,   _UpperCamelCase	:int    ,   _UpperCamelCase	:Tuple )->					int:
         __A          =				ConvNextVaForImageClassification(_UpperCamelCase )
         model.to(_UpperCamelCase )
         model.eval()
         __A          =				model(_UpperCamelCase    ,   labels=_UpperCamelCase )
         self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.num_labels) )




   def _lowerCAmelCase      (self	:List[str]    ,   _UpperCamelCase	:Tuple    ,   _UpperCamelCase	:List[Any]    ,   _UpperCamelCase	:Optional[Any] )->					Any:
         __A          =				ConvNextVaBackbone(config=_UpperCamelCase )
         model.to(_UpperCamelCase )
         model.eval()
         __A          =				model(_UpperCamelCase )

         # verify hidden states
         self.parent.assertEqual(len(result.feature_maps )    ,   len(config.out_features ) )
         self.parent.assertListEqual(list(result.feature_maps[0].shape )    ,   [self.batch_size, self.hidden_sizes[1], 4, 4] )

         # verify channels
         self.parent.assertEqual(len(model.channels )    ,   len(config.out_features ) )
         self.parent.assertListEqual(model.channels    ,   config.hidden_sizes[1:] )

         # verify backbone works with out_features=None
         __A          =				None
         __A          =				ConvNextVaBackbone(config=_UpperCamelCase )
         model.to(_UpperCamelCase )
         model.eval()
         __A          =				model(_UpperCamelCase )

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps )    ,   1 )
         self.parent.assertListEqual(list(result.feature_maps[0].shape )    ,   [self.batch_size, self.hidden_sizes[-1], 1, 1] )

         # verify channels
         self.parent.assertEqual(len(model.channels )    ,   1 )
         self.parent.assertListEqual(model.channels    ,   [config.hidden_sizes[-1]] )




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






   def _lowerCAmelCase      (self	:List[Any] )->					Tuple:
         __A          =				self.prepare_config_and_inputs()
         __A   ,						__A   ,						__A          =				config_and_inputs
         __A          =				{'''pixel_values''': pixel_values, '''labels''': labels}
         return config, inputs_dict





@require_torch
class A_					(			_lowerCamelCase ,      _lowerCamelCase ,      unittest.TestCase   ):
   lowerCAmelCase__        = (
       (
           ConvNextVaModel,
           ConvNextVaForImageClassification,
           ConvNextVaBackbone,
       )
       if is_torch_available()
       else ()
   )
   lowerCAmelCase__        = (
       {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
       if is_torch_available()
       else {}
   )

   lowerCAmelCase__        = False
   lowerCAmelCase__        = False
   lowerCAmelCase__        = False
   lowerCAmelCase__        = False
   lowerCAmelCase__        = False




   def _lowerCAmelCase      (self	:Union[str, Any] )->					Any:
         __A          =				ConvNextVaModelTester(self )
         __A          =				ConfigTester(self    ,   config_class=_UpperCamelCase    ,   has_text_modality=_UpperCamelCase    ,   hidden_size=37 )




   def _lowerCAmelCase      (self	:Optional[Any] )->					Tuple:
         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 _lowerCAmelCase      (self	:Any )->					Any:
         return




   @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' )
   def _lowerCAmelCase      (self	:Tuple )->					int:
         pass




   @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' )
   def _lowerCAmelCase      (self	:Any )->					str:
         pass




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




   def _lowerCAmelCase      (self	:Tuple )->					int:
         if not self.model_tester.is_training:
               return

         for model_class in self.all_model_classes:
               __A   ,						__A          =				self.model_tester.prepare_config_and_inputs_with_labels()
               __A          =				True

               if model_class.__name__ in [
                   *get_values(_UpperCamelCase ),
                   *get_values(_UpperCamelCase ),
               ]:
                     continue

               __A          =				model_class(_UpperCamelCase )
               model.to(_UpperCamelCase )
               model.train()
               __A          =				self._prepare_for_class(_UpperCamelCase    ,   _UpperCamelCase    ,   return_labels=_UpperCamelCase )
               __A          =				model(**_UpperCamelCase ).loss
               loss.backward()




   def _lowerCAmelCase      (self	:str )->					Optional[int]:
         if not self.model_tester.is_training:
               return

         for model_class in self.all_model_classes:
               __A   ,						__A          =				self.model_tester.prepare_config_and_inputs_with_labels()
               __A          =				False
               __A          =				True

               if (
                   model_class.__name__
                   in [*get_values(_UpperCamelCase ), *get_values(_UpperCamelCase )]
                   or not model_class.supports_gradient_checkpointing
               ):
                     continue

               __A          =				model_class(_UpperCamelCase )
               model.to(_UpperCamelCase )
               model.gradient_checkpointing_enable()
               model.train()
               __A          =				self._prepare_for_class(_UpperCamelCase    ,   _UpperCamelCase    ,   return_labels=_UpperCamelCase )
               __A          =				model(**_UpperCamelCase ).loss
               loss.backward()




   def _lowerCAmelCase      (self	:Optional[int] )->					Tuple:
         __A   ,						__A          =				self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               __A          =				model_class(_UpperCamelCase )
               __A          =				inspect.signature(model.forward )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __A          =				[*signature.parameters.keys()]

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




   def _lowerCAmelCase      (self	:Optional[Any] )->					Optional[Any]:
         __A          =				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_UpperCamelCase )




   def _lowerCAmelCase      (self	:List[Any] )->					Optional[Any]:
         def check_hidden_states_output(_UpperCamelCase	:Tuple    ,   _UpperCamelCase	:Union[str, Any]    ,   _UpperCamelCase	:int ):
               __A          =				model_class(_UpperCamelCase )
               model.to(_UpperCamelCase )
               model.eval()

               with torch.no_grad():
                     __A          =				model(**self._prepare_for_class(_UpperCamelCase    ,   _UpperCamelCase ) )

               __A          =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               __A          =				self.model_tester.num_stages
               self.assertEqual(len(_UpperCamelCase )    ,   expected_num_stages + 1 )

               # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:] )    ,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,   )

         __A   ,						__A          =				self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               __A          =				True
               check_hidden_states_output(_UpperCamelCase    ,   _UpperCamelCase    ,   _UpperCamelCase )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __A          =				True

               check_hidden_states_output(_UpperCamelCase    ,   _UpperCamelCase    ,   _UpperCamelCase )




   def _lowerCAmelCase      (self	:Tuple )->					Any:
         __A          =				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase )






   @slow
   def _lowerCAmelCase      (self	:Optional[Any] )->					str:
         for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A          =				ConvNextVaModel.from_pretrained(_UpperCamelCase )
               self.assertIsNotNone(_UpperCamelCase )





def _a				(	)	->						int:







      '''simple docstring'''






      __A          =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
      return image







@require_torch
@require_vision
class A_					(			unittest.TestCase   ):




   @cached_property
   def _lowerCAmelCase      (self	:Dict )->					Union[str, Any]:
         return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None






   @slow
   def _lowerCAmelCase      (self	:int )->					Tuple:
         __A          =				ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_UpperCamelCase )

         __A          =				self.default_image_processor
         __A          =				prepare_img()
         __A          =				preprocessor(images=_UpperCamelCase    ,   return_tensors='''pt''' ).to(_UpperCamelCase )

         # forward pass
         with torch.no_grad():
               __A          =				model(**_UpperCamelCase )

         # verify the logits
         __A          =				torch.Size((1, 1000) )
         self.assertEqual(outputs.logits.shape    ,   _UpperCamelCase )

         __A          =				torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6] ).to(_UpperCamelCase )
         self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,   _UpperCamelCase    ,   atol=1e-4 ) )












from pathlib import Path

import cva
import numpy as np
from matplotlib import pyplot as plt



def _a				(	lowerCamelCase:   np.ndarray					,				lowerCamelCase:   np.ndarray					,				lowerCamelCase:   np.ndarray					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						np.ndarray:







      '''simple docstring'''






      __A          =				cva.getAffineTransform(lowerCamelCase					,				lowerCamelCase )
      return cva.warpAffine(lowerCamelCase					,				lowerCamelCase					,				(rows, cols) )


if __name__ == "__main__":
       # read original image
       snake_case__					:							List[Any]													=     cva.imread(
           str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg')
       )
       # turn image in gray scale value
       snake_case__					:							List[str]													=     cva.cvtColor(image, cva.COLOR_BGR2GRAY)
       # get image shape
       snake_case__						,    snake_case__					:							str													=     gray_img.shape

       # set different points to rotate image
       snake_case__					:							Any													=     np.array([[50, 50], [200, 50], [50, 200]], np.floataa)
       snake_case__					:							str													=     np.array([[10, 100], [200, 50], [100, 250]], np.floataa)
       snake_case__					:							int													=     np.array([[50, 50], [150, 50], [120, 200]], np.floataa)
       snake_case__					:							List[str]													=     np.array([[10, 100], [80, 50], [180, 250]], np.floataa)

       # add all rotated images in a list
       snake_case__					:							Optional[Any]													=     [
           gray_img,
           get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
           get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
           get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
       ]

       # plot different image rotations
       snake_case__					:							Optional[Any]													=     plt.figure(1)
       snake_case__					:							Dict													=     ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3']
       for i, image in enumerate(images):
              plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray')
              plt.title(titles[i])
              plt.axis('off')
              plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95)
       plt.show()





