

import inspect
import unittest

from transformers import ResNetConfig
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_backbone_common import BackboneTesterMixin
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 torch import nn

   from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
   from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor



class 						lowercase_					:



      def __init__(    self   :       Optional[Any]    ,      A__   :       int    ,      A__   :       List[str]=3    ,      A__   :       Dict=32    ,      A__   :       Dict=3    ,      A__   :       Optional[Any]=10    ,      A__   :       List[str]=[10, 20, 30, 40]    ,      A__   :       int=[1, 1, 2, 1]    ,      A__   :       Optional[int]=True    ,      A__   :       Optional[Any]=True    ,      A__   :       Dict="relu"    ,      A__   :       List[Any]=3    ,      A__   :       Any=None    ,      A__   :       Optional[Any]=["stage2", "stage3", "stage4"]    ,      A__   :       int=[2, 3, 4]    ,      )					->  Union[str, Any]:
        _snake_case		=							parent
        _snake_case		=							batch_size
        _snake_case		=							image_size
        _snake_case		=							num_channels
        _snake_case		=							embeddings_size
        _snake_case		=							hidden_sizes
        _snake_case		=							depths
        _snake_case		=							is_training
        _snake_case		=							use_labels
        _snake_case		=							hidden_act
        _snake_case		=							num_labels
        _snake_case		=							scope
        _snake_case		=							len(A__	)
        _snake_case		=							out_features
        _snake_case		=							out_indices



      def 		UpperCamelCase_	(    self   :       str	)					->  Tuple:
        _snake_case		=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

        _snake_case		=							self.get_config()

        return config, pixel_values, labels



      def 		UpperCamelCase_	(    self   :       Tuple	)					->  str:
        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    ,      out_features=self.out_features    ,      out_indices=self.out_indices    ,      )



      def 		UpperCamelCase_	(    self   :       Tuple    ,      A__   :       int    ,      A__   :       List[str]    ,      A__   :       Any	)					->  List[Any]:
        _snake_case		=							ResNetModel(config=A__	)
        model.to(A__	)
        model.eval()
        _snake_case		=							model(A__	)
        # 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 		UpperCamelCase_	(    self   :       Union[str, Any]    ,      A__   :       str    ,      A__   :       List[str]    ,      A__   :       Any	)					->  Optional[int]:
        _snake_case		=							self.num_labels
        _snake_case		=							ResNetForImageClassification(A__	)
        model.to(A__	)
        model.eval()
        _snake_case		=							model(A__    ,      labels=A__	)
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.num_labels)	)



      def 		UpperCamelCase_	(    self   :       str    ,      A__   :       str    ,      A__   :       str    ,      A__   :       Tuple	)					->  Optional[Any]:
        _snake_case		=							ResNetBackbone(config=A__	)
        model.to(A__	)
        model.eval()
        _snake_case		=							model(A__	)

        # verify feature maps
        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
        _snake_case		=							None
        _snake_case		=							ResNetBackbone(config=A__	)
        model.to(A__	)
        model.eval()
        _snake_case		=							model(A__	)

        # 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 		UpperCamelCase_	(    self   :       Any	)					->  Union[str, Any]:
        _snake_case		=							self.prepare_config_and_inputs()
        _snake_case		=							config_and_inputs
        _snake_case		=							{"pixel_values": pixel_values}
        return config, inputs_dict



@require_torch
class 						lowercase_					(						A__     ,							A__     ,							unittest.TestCase  ):
      UpperCamelCase_    :	int		   =       (
          (
              ResNetModel,
              ResNetForImageClassification,
              ResNetBackbone,
          )
          if is_torch_available()
          else ()
      )
      UpperCamelCase_    :	str		   =       (
          {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
          if is_torch_available()
          else {}
      )

      UpperCamelCase_    :	List[Any]		   =       True
      UpperCamelCase_    :	Union[str, Any]		   =       False
      UpperCamelCase_    :	List[str]		   =       False
      UpperCamelCase_    :	str		   =       False
      UpperCamelCase_    :	List[str]		   =       False



      def 		UpperCamelCase_	(    self   :       Optional[int]	)					->  Tuple:
        _snake_case		=							ResNetModelTester(self	)
        _snake_case		=							ConfigTester(self    ,      config_class=A__    ,      has_text_modality=A__	)



      def 		UpperCamelCase_	(    self   :       Dict	)					->  Union[str, 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 		UpperCamelCase_	(    self   :       int	)					->  List[str]:
        return



      @unittest.skip(reason='''ResNet does not use inputs_embeds'''	)
      def 		UpperCamelCase_	(    self   :       Tuple	)					->  Optional[Any]:
        pass



      @unittest.skip(reason='''ResNet does not support input and output embeddings'''	)
      def 		UpperCamelCase_	(    self   :       int	)					->  Optional[int]:
        pass



      def 		UpperCamelCase_	(    self   :       Union[str, Any]	)					->  Dict:
        _snake_case		=							self.model_tester.prepare_config_and_inputs_for_common()

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

          _snake_case		=							["pixel_values"]
          self.assertListEqual(arg_names[:1]    ,      A__	)



      def 		UpperCamelCase_	(    self   :       List[str]	)					->  int:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A__	)



      def 		UpperCamelCase_	(    self   :       List[Any]	)					->  int:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*A__	)



      def 		UpperCamelCase_	(    self   :       Any	)					->  Optional[Any]:
        _snake_case		=							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          _snake_case		=							model_class(config=A__	)
          for name, module in model.named_modules():
            if isinstance(A__    ,      (nn.BatchNormad, nn.GroupNorm)	):
              self.assertTrue(
                  torch.all(module.weight == 1	)    ,      msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""    ,      )
              self.assertTrue(
                  torch.all(module.bias == 0	)    ,      msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""    ,      )



      def 		UpperCamelCase_	(    self   :       int	)					->  Optional[int]:






        def check_hidden_states_output(A__   :       List[Any]    ,      A__   :       Optional[int]    ,      A__   :       Optional[int]	):
          _snake_case		=							model_class(A__	)
          model.to(A__	)
          model.eval()

          with torch.no_grad():
            _snake_case		=							model(**self._prepare_for_class(A__    ,      A__	)	)

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

          _snake_case		=							self.model_tester.num_stages
          self.assertEqual(len(A__	)    ,      expected_num_stages + 1	)

          # ResNet'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]    ,      )

        _snake_case		=							self.model_tester.prepare_config_and_inputs_for_common()
        _snake_case		=							["basic", "bottleneck"]
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            _snake_case		=							layer_type
            _snake_case		=							True
            check_hidden_states_output(A__    ,      A__    ,      A__	)

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

            check_hidden_states_output(A__    ,      A__    ,      A__	)



      @unittest.skip(reason='''ResNet does not use feedforward chunking'''	)
      def 		UpperCamelCase_	(    self   :       Optional[int]	)					->  Optional[Any]:
        pass



      def 		UpperCamelCase_	(    self   :       int	)					->  Union[str, Any]:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*A__	)







      @slow
      def 		UpperCamelCase_	(    self   :       Dict	)					->  Optional[int]:






        for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _snake_case		=							ResNetModel.from_pretrained(A__	)
          self.assertIsNotNone(A__	)



def    snake_case_()							->			int:



  """simple docstring"""






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



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



      @cached_property
      def 		UpperCamelCase_	(    self   :       Optional[Any]	)					->  Union[str, Any]:
        return (
            AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
            if is_vision_available()
            else None
        )







      @slow
      def 		UpperCamelCase_	(    self   :       Union[str, Any]	)					->  Dict:
        _snake_case		=							ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(A__	)

        _snake_case		=							self.default_image_processor
        _snake_case		=							prepare_img()
        _snake_case		=							image_processor(images=A__    ,      return_tensors='''pt'''	).to(A__	)

        # forward pass
        with torch.no_grad():
          _snake_case		=							model(**A__	)

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

        _snake_case		=							torch.tensor([-11.1069, -9.7877, -8.3777]	).to(A__	)

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



@require_torch
class 						lowercase_					(						A__     ,							unittest.TestCase  ):
      UpperCamelCase_    :	str		   =       (ResNetBackbone,) if is_torch_available() else ()
      UpperCamelCase_    :	Any		   =       False
      UpperCamelCase_    :	Optional[Any]		   =       ResNetConfig



      def 		UpperCamelCase_	(    self   :       Optional[int]	)					->  List[Any]:
        _snake_case		=							ResNetModelTester(self	)




import random
import sys

from . import cryptomath_module as cryptomath

__A    	=			(
    r''' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`'''
    r'''abcdefghijklmnopqrstuvwxyz{|}~'''
)



def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )							->			None:



  """simple docstring"""






  if mode == "encrypt":
    if key_a == 1:
      sys.exit(
          '''The affine cipher becomes weak when key '''
          '''A is set to 1. Choose different key'''  )
    if key_b == 0:
      sys.exit(
          '''The affine cipher becomes weak when key '''
          '''B is set to 0. Choose different key'''  )
  if key_a < 0 or key_b < 0 or key_b > len(_UpperCamelCase  ) - 1:
    sys.exit(
        '''Key A must be greater than 0 and key B must '''
        F"""be between 0 and {len(_UpperCamelCase  ) - 1}."""  )
  if cryptomath.gcd(_UpperCamelCase				, len(_UpperCamelCase  )  ) != 1:
    sys.exit(
        F"""Key A {key_a} and the symbol set size {len(_UpperCamelCase  )} """
        '''are not relatively prime. Choose a different key.'''  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			str:



  """simple docstring"""






  _snake_case,  _snake_case		=							divmod(_UpperCamelCase				, len(_UpperCamelCase  )  )
  check_keys(_UpperCamelCase				, _UpperCamelCase				, '''encrypt'''  )
  _snake_case		=							''''''
  for symbol in message:
    if symbol in SYMBOLS:
      _snake_case		=							SYMBOLS.find(_UpperCamelCase  )
      cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(_UpperCamelCase  )]
    else:
      cipher_text += symbol
  return cipher_text



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			str:



  """simple docstring"""






  _snake_case,  _snake_case		=							divmod(_UpperCamelCase				, len(_UpperCamelCase  )  )
  check_keys(_UpperCamelCase				, _UpperCamelCase				, '''decrypt'''  )
  _snake_case		=							''''''
  _snake_case		=							cryptomath.find_mod_inverse(_UpperCamelCase				, len(_UpperCamelCase  )  )
  for symbol in message:
    if symbol in SYMBOLS:
      _snake_case		=							SYMBOLS.find(_UpperCamelCase  )
      plain_text += SYMBOLS[
          (sym_index - key_b) * mod_inverse_of_key_a % len(_UpperCamelCase  )
      ]
    else:
      plain_text += symbol
  return plain_text



def    snake_case_()							->			int:



  """simple docstring"""






  while True:
    _snake_case		=							random.randint(2				, len(_UpperCamelCase  )  )
    _snake_case		=							random.randint(2				, len(_UpperCamelCase  )  )
    if cryptomath.gcd(_UpperCamelCase				, len(_UpperCamelCase  )  ) == 1 and key_b % len(_UpperCamelCase  ) != 0:
      return key_b * len(_UpperCamelCase  ) + key_b



def    snake_case_()							->			None:



  """simple docstring"""






  _snake_case		=							input('''Enter message: '''  ).strip()
  _snake_case		=							int(input('''Enter key [2000 - 9000]: '''  ).strip()  )
  _snake_case		=							input('''Encrypt/Decrypt [E/D]: '''  ).strip().lower()

  if mode.startswith('''e'''  ):
    _snake_case		=							'''encrypt'''
    _snake_case		=							encrypt_message(_UpperCamelCase				, _UpperCamelCase  )
  elif mode.startswith('''d'''  ):
    _snake_case		=							'''decrypt'''
    _snake_case		=							decrypt_message(_UpperCamelCase				, _UpperCamelCase  )
  print(F"""\n{mode.title()}ed text: \n{translated}"""  )


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 # main()

