

"""simple docstring"""






import inspect
import unittest

from transformers import ViTMSNConfig
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 torch import nn

 from transformers import ViTMSNForImageClassification, ViTMSNModel
 from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor







class 	__UpperCamelCase    :

  def __init__(		self    ,_A    ,_A=13    ,_A=30    ,_A=2    ,_A=3    ,_A=True    ,_A=True    ,_A=32    ,_A=5    ,_A=4    ,_A=37    ,_A="gelu"    ,_A=0.1    ,_A=0.1    ,_A=10    ,_A=0.0_2    ,_A=None    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    parent
      _lowerCAmelCase       :   Any  =    batch_size
      _lowerCAmelCase       :   List[str]  =    image_size
      _lowerCAmelCase       :   List[Any]  =    patch_size
      _lowerCAmelCase       :   Tuple  =    num_channels
      _lowerCAmelCase       :   Union[str, Any]  =    is_training
      _lowerCAmelCase       :   Tuple  =    use_labels
      _lowerCAmelCase       :   Dict  =    hidden_size
      _lowerCAmelCase       :   Optional[int]  =    num_hidden_layers
      _lowerCAmelCase       :   Optional[int]  =    num_attention_heads
      _lowerCAmelCase       :   Union[str, Any]  =    intermediate_size
      _lowerCAmelCase       :   Optional[Any]  =    hidden_act
      _lowerCAmelCase       :   Optional[Any]  =    hidden_dropout_prob
      _lowerCAmelCase       :   str  =    attention_probs_dropout_prob
      _lowerCAmelCase       :   str  =    type_sequence_label_size
      _lowerCAmelCase       :   Dict  =    initializer_range
      _lowerCAmelCase       :   Optional[int]  =    scope

      # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
      _lowerCAmelCase       :   List[Any]  =    (image_size // patch_size) ** 2
      _lowerCAmelCase       :   str  =    num_patches + 1

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

      _lowerCAmelCase       :   Optional[Any]  =    None
      if self.use_labels:
          _lowerCAmelCase       :   List[str]  =    ids_tensor([self.batch_size]    ,self.type_sequence_label_size      )

      _lowerCAmelCase       :   Union[str, Any]  =    self.get_config()

      return config, pixel_values, labels

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return ViTMSNConfig(
          image_size=self.image_size    ,patch_size=self.patch_size    ,num_channels=self.num_channels    ,hidden_size=self.hidden_size    ,num_hidden_layers=self.num_hidden_layers    ,num_attention_heads=self.num_attention_heads    ,intermediate_size=self.intermediate_size    ,hidden_act=self.hidden_act    ,hidden_dropout_prob=self.hidden_dropout_prob    ,attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,initializer_range=self.initializer_range    ,)

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    ViTMSNModel(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Dict  =    model(_A      )
      self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self.type_sequence_label_size
      _lowerCAmelCase       :   str  =    ViTMSNForImageClassification(_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Optional[Any]  =    model(_A    ,labels=_A      )
      print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}'      )
      print('Labels: {labels}'      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.type_sequence_label_size)      )

      # test greyscale images
      _lowerCAmelCase       :   str  =    1
      _lowerCAmelCase       :   Dict  =    ViTMSNForImageClassification(_A      )
      model.to(_A      )
      model.eval()

      _lowerCAmelCase       :   Optional[Any]  =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
      _lowerCAmelCase       :   Optional[int]  =    model(_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.type_sequence_label_size)      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







@require_torch
class 	__UpperCamelCase    (    a__							,							a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
  _UpperCAmelCase          =		(
      {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification}
      if is_torch_available()
      else {}
  )

  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    ViTMSNModelTester(self      )
      _lowerCAmelCase       :   str  =    ConfigTester(self    ,config_class=_A    ,has_text_modality=_A    ,hidden_size=37      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.config_tester.run_common_tests()

  @unittest.skip(reason='ViTMSN does not use inputs_embeds'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

      for model_class in self.all_model_classes:
          _lowerCAmelCase       :   Optional[int]  =    model_class(_A      )
          self.assertIsInstance(model.get_input_embeddings()    ,(nn.Module)      )
          _lowerCAmelCase       :   Tuple  =    model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(_A    ,nn.Linear      )      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase,					_lowerCAmelCase       :   List[Any]  =    self.model_tester.prepare_config_and_inputs_for_common()

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

          _lowerCAmelCase       :   Optional[int]  =    ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_A      )







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _lowerCAmelCase       :   Tuple  =    ViTMSNModel.from_pretrained(_A      )
          self.assertIsNotNone(_A      )





def 		lowerCamelCase__		(					):

    '''simple docstring'''



    _lowerCAmelCase       :   List[Any]  =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
    return image







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

  @cached_property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return ViTImageProcessor.from_pretrained('facebook/vit-msn-small'      ) if is_vision_available() else None







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(2      )
      _lowerCAmelCase       :   Dict  =    ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small'      ).to(_A      )

      _lowerCAmelCase       :   Any  =    self.default_image_processor
      _lowerCAmelCase       :   Dict  =    prepare_img()
      _lowerCAmelCase       :   int  =    image_processor(images=_A    ,return_tensors='pt'      ).to(_A      )

      # forward pass
      with torch.no_grad():
          _lowerCAmelCase       :   List[str]  =    model(**_A      )

      # verify the logits
      _lowerCAmelCase       :   Dict  =    torch.Size((1, 1000)      )
      self.assertEqual(outputs.logits.shape    ,_A      )

      _lowerCAmelCase       :   int  =    torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5]      ).to(_A      )

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








"""simple docstring"""






import argparse
import struct
import unittest







class 	__UpperCamelCase    :

  def __init__(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    data

      # Initialize hash values
      _lowerCAmelCase       :   Any  =    [
          0x6A09_E667,
          0xBB67_AE85,
          0x3C6E_F372,
          0xA54F_F53A,
          0x510E_527F,
          0x9B05_688C,
          0x1F83_D9AB,
          0x5BE0_CD19,
      ]

      # Initialize round constants
      _lowerCAmelCase       :   str  =    [
          0x428A_2F98,
          0x7137_4491,
          0xB5C0_FBCF,
          0xE9B5_DBA5,
          0x3956_C25B,
          0x59F1_11F1,
          0x923F_82A4,
          0xAB1C_5ED5,
          0xD807_AA98,
          0x1283_5B01,
          0x2431_85BE,
          0x550C_7DC3,
          0x72BE_5D74,
          0x80DE_B1FE,
          0x9BDC_06A7,
          0xC19B_F174,
          0xE49B_69C1,
          0xEFBE_4786,
          0x0FC1_9DC6,
          0x240C_A1CC,
          0x2DE9_2C6F,
          0x4A74_84AA,
          0x5CB0_A9DC,
          0x76F9_88DA,
          0x983E_5152,
          0xA831_C66D,
          0xB003_27C8,
          0xBF59_7FC7,
          0xC6E0_0BF3,
          0xD5A7_9147,
          0x06CA_6351,
          0x1429_2967,
          0x27B7_0A85,
          0x2E1B_2138,
          0x4D2C_6DFC,
          0x5338_0D13,
          0x650A_7354,
          0x766A_0ABB,
          0x81C2_C92E,
          0x9272_2C85,
          0xA2BF_E8A1,
          0xA81A_664B,
          0xC24B_8B70,
          0xC76C_51A3,
          0xD192_E819,
          0xD699_0624,
          0xF40E_3585,
          0x106A_A070,
          0x19A4_C116,
          0x1E37_6C08,
          0x2748_774C,
          0x34B0_BCB5,
          0x391C_0CB3,
          0x4ED8_AA4A,
          0x5B9C_CA4F,
          0x682E_6FF3,
          0x748F_82EE,
          0x78A5_636F,
          0x84C8_7814,
          0x8CC7_0208,
          0x90BE_FFFA,
          0xA450_6CEB,
          0xBEF9_A3F7,
          0xC671_78F2,
      ]

      _lowerCAmelCase       :   Any  =    self.preprocessing(self.data      )
      self.final_hash()

  @staticmethod
  def __lowerCamelCase		(		_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    b'\x80' + (b'\x00' * (63 - (len(_A      ) + 8) % 64))
      _lowerCAmelCase       :   Any  =    struct.pack('>Q'    ,(len(_A      ) * 8)      )
      return data + padding + big_endian_integer

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    [
          self.preprocessed_data[x : x + 64]
          for x in range(0    ,len(self.preprocessed_data      )    ,64      )
      ]

      for block in self.blocks:
          # Convert the given block into a list of 4 byte integers
          _lowerCAmelCase       :   int  =    list(struct.unpack('>16L'    ,_A      )      )
          # add 48 0-ed integers
          words += [0] * 48

          _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    self.hashes

          for index in range(0    ,64      ):
              if index > 15:
                  # modify the zero-ed indexes at the end of the array
                  _lowerCAmelCase       :   List[str]  =    (
                      self.ror(words[index - 15]    ,7      )
                      ^ self.ror(words[index - 15]    ,18      )
                      ^ (words[index - 15] >> 3)
                  )
                  _lowerCAmelCase       :   Tuple  =    (
                      self.ror(words[index - 2]    ,17      )
                      ^ self.ror(words[index - 2]    ,19      )
                      ^ (words[index - 2] >> 10)
                  )

                  _lowerCAmelCase       :   str  =    (
                      words[index - 16] + sa + words[index - 7] + sa
                  ) % 0x1_0000_0000

              # Compression
              _lowerCAmelCase       :   Optional[Any]  =    self.ror(_A    ,6      ) ^ self.ror(_A    ,11      ) ^ self.ror(_A    ,25      )
              _lowerCAmelCase       :   int  =    (e & f) ^ ((~e & 0xFFFF_FFFF) & g)
              _lowerCAmelCase       :   int  =    (
                  h + sa + ch + self.round_constants[index] + words[index]
              ) % 0x1_0000_0000
              _lowerCAmelCase       :   Union[str, Any]  =    self.ror(_A    ,2      ) ^ self.ror(_A    ,13      ) ^ self.ror(_A    ,22      )
              _lowerCAmelCase       :   Any  =    (a & b) ^ (a & c) ^ (b & c)
              _lowerCAmelCase       :   Any  =    (sa + maj) % 0x1_0000_0000

              _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    (
                  g,
                  f,
                  e,
                  ((d + tempa) % 0x1_0000_0000),
                  c,
                  b,
                  a,
                  ((tempa + tempa) % 0x1_0000_0000),
              )

          _lowerCAmelCase       :   Any  =    [a, b, c, d, e, f, g, h]

          # Modify final values
          _lowerCAmelCase       :   int  =    [
              ((element + mutated_hash_values[index]) % 0x1_0000_0000)
              for index, element in enumerate(self.hashes      )
          ]

      _lowerCAmelCase       :   List[str]  =    ''.join([hex(_A      )[2:].zfill(8      ) for value in self.hashes]      )







  def __lowerCamelCase		(		self    ,_A    ,_A      ):
      '''simple docstring'''

      return 0xFFFF_FFFF & (value << (32 - rotations)) | (value >> rotations)







class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      import hashlib

      _lowerCAmelCase       :   Any  =    bytes('Test String'    ,'utf-8'      )
      self.assertEqual(SHAaaa(_A      ).hash    ,hashlib.shaaaa(_A      ).hexdigest()      )





def 		lowerCamelCase__		(					):

    '''simple docstring'''



    import doctest

    doctest.testmod()

    _lowerCAmelCase       :   Optional[Any]  =    argparse.ArgumentParser()
    parser.add_argument(
        '-s' ,   '--string' ,   dest='input_string' ,   default='Hello World!! Welcome to Cryptography' ,   help='Hash the string' ,   )
    parser.add_argument(
        '-f' ,   '--file' ,   dest='input_file' ,   help='Hash contents of a file'   )

    _lowerCAmelCase       :   Tuple  =    parser.parse_args()

    _lowerCAmelCase       :   List[str]  =    args.input_string

    # hash input should be a bytestring
    if args.input_file:
        with open(args.input_file ,   'rb'   ) as f:
            _lowerCAmelCase       :   int  =    f.read()
    else:
        _lowerCAmelCase       :   int  =    bytes(_lowerCamelCase ,   'utf-8'   )

    print(SHAaaa(_lowerCamelCase   ).hash   )


if __name__ == "__main__":
 main()





