





import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
   from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image




class 			__UpperCamelCase    :





     def __init__(     self				,							_UpperCamelCase				,							_UpperCamelCase=13				,							_UpperCamelCase=64				,							_UpperCamelCase=2				,							_UpperCamelCase=3				,							_UpperCamelCase=True				,							_UpperCamelCase=True				,							_UpperCamelCase=32				,							_UpperCamelCase=5				,							_UpperCamelCase=4				,							_UpperCamelCase=37				,							_UpperCamelCase="gelu"				,							_UpperCamelCase=0.1				,							_UpperCamelCase=0.1				,							_UpperCamelCase=10				,							_UpperCamelCase=0.02				,							_UpperCamelCase=[1, 16, 4, 4]				,							_UpperCamelCase=None				,							):
        _UpperCAmelCase           =   parent
        _UpperCAmelCase           =   batch_size
        _UpperCAmelCase           =   image_size
        _UpperCAmelCase           =   patch_size
        _UpperCAmelCase           =   num_channels
        _UpperCAmelCase           =   is_training
        _UpperCAmelCase           =   use_labels
        _UpperCAmelCase           =   hidden_size
        _UpperCAmelCase           =   num_hidden_layers
        _UpperCAmelCase           =   num_attention_heads
        _UpperCAmelCase           =   intermediate_size
        _UpperCAmelCase           =   hidden_act
        _UpperCAmelCase           =   hidden_dropout_prob
        _UpperCAmelCase           =   attention_probs_dropout_prob
        _UpperCAmelCase           =   type_sequence_label_size
        _UpperCAmelCase           =   initializer_range
        _UpperCAmelCase           =   scope
        _UpperCAmelCase           =   backbone_featmap_shape

        # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        # the number of patches is based on the feature map of the backbone, which by default uses an output stride
        # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
        _UpperCAmelCase           =   (self.image_size // 32) ** 2
        _UpperCAmelCase           =   num_patches + 1





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

        _UpperCAmelCase           =   None
        if self.use_labels:
           _UpperCAmelCase           =   ids_tensor([self.batch_size]				,							self.type_sequence_label_size					)

        _UpperCAmelCase           =   self.get_config()

        return config, pixel_values, labels





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   {
            '''global_padding''': '''same''',
            '''layer_type''': '''bottleneck''',
            '''depths''': [3, 4, 9],
            '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
            '''embedding_dynamic_padding''': True,
            '''hidden_sizes''': [4, 8, 16, 32],
            '''num_groups''': 2,
        }

        return ViTHybridConfig(
            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				,							is_decoder=_UpperCamelCase				,							initializer_range=self.initializer_range				,							backbone_featmap_shape=self.backbone_featmap_shape				,							backbone_config=_UpperCamelCase				,							)





     def 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        _UpperCAmelCase           =   ViTHybridModel(config=_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase					)
        self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)					)





     def 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        _UpperCAmelCase           =   self.type_sequence_label_size
        _UpperCAmelCase           =   ViTHybridForImageClassification(_UpperCamelCase					)
        model.to(_UpperCamelCase					)
        model.eval()
        _UpperCAmelCase           =   model(_UpperCamelCase				,							labels=_UpperCamelCase					)
        self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.prepare_config_and_inputs()
        _UpperCAmelCase       ,      _UpperCAmelCase       ,      _UpperCAmelCase           =   config_and_inputs
        _UpperCAmelCase           =   {'''pixel_values''': pixel_values}
        return config, inputs_dict




@require_torch
class 			__UpperCamelCase    (							A__	, A__	, unittest.TestCase    ):
     __A	:  Tuple							  =   (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
     __A	:  Tuple							  =   (
         {"""feature-extraction""": ViTHybridModel, """image-classification""": ViTHybridForImageClassification}
         if is_torch_available()
         else {}
     )
     __A	:  Optional[Any]							  =   False
     __A	:  Optional[int]							  =   False
     __A	:  int							  =   False





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   ViTHybridModelTester(self					)
        _UpperCAmelCase           =   ConfigTester(self				,							config_class=_UpperCamelCase				,							has_text_modality=_UpperCamelCase				,							hidden_size=37					)





     def 		UpperCamelCase(     self					):
        self.config_tester.run_common_tests()





     @unittest.skip(reason='''ViT does not use inputs_embeds'''					)
     def 		UpperCamelCase(     self					):
        pass





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase       ,      _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           _UpperCAmelCase           =   model_class(_UpperCamelCase					)
           self.assertIsInstance(model.get_input_embeddings()				,							(nn.Module)					)
           _UpperCAmelCase           =   model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(_UpperCamelCase				,							nn.Linear					)					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase       ,      _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs_for_common()

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

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





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_UpperCamelCase					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase					)





     def 		UpperCamelCase(     self					):
        _UpperCAmelCase       ,      _UpperCAmelCase           =   self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCAmelCase           =   _config_zero_init(_UpperCamelCase					)
        for model_class in self.all_model_classes:
           _UpperCAmelCase           =   model_class(config=_UpperCamelCase					)
           # Skip the check for the backbone
           for name, module in model.named_modules():
              if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
                 _UpperCAmelCase           =   [f'''{name}.{key}''' for key in module.state_dict().keys()]
                 break

           for name, param in model.named_parameters():
              if param.requires_grad:
                 if name in backbone_params:
                    continue
                 self.assertIn(
                     ((param.data.mean() * 1e9).round() / 1e9).item()				,							[0.0, 1.0]				,							msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''				,							)





     @slow
     def 		UpperCamelCase(     self					):
        for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _UpperCAmelCase           =   ViTHybridModel.from_pretrained(_UpperCamelCase					)
           self.assertIsNotNone(_UpperCamelCase					)




def      A__       (    )  ->  Optional[Any]:






   """simple docstring"""







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




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





     @cached_property
     def 		UpperCamelCase(     self					):
        return (
            ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
            if is_vision_available()
            else None
        )





     @slow
     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(
            _UpperCamelCase					)

        _UpperCAmelCase           =   self.default_image_processor
        _UpperCAmelCase           =   prepare_img()
        _UpperCAmelCase           =   image_processor(images=_UpperCamelCase				,							return_tensors='''pt'''					).to(_UpperCamelCase					)

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

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

        _UpperCAmelCase           =   torch.tensor([-1.9090, -0.4993, -0.2389]					).to(_UpperCamelCase					)

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





     @slow
     @require_accelerate
     def 		UpperCamelCase(     self					):
        _UpperCAmelCase           =   ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384'''					)
        _UpperCAmelCase           =   ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384'''				,							device_map='''auto'''					)

        _UpperCAmelCase           =   prepare_img()

        _UpperCAmelCase           =   image_processor(images=_UpperCamelCase				,							return_tensors='''pt'''					)
        _UpperCAmelCase           =   model(**_UpperCamelCase					)
        _UpperCAmelCase           =   outputs.logits
        # model predicts one of the 1000 ImageNet classes
        _UpperCAmelCase           =   logits.argmax(-1					).item()

        self.assertTrue(model.config.idalabel[predicted_class_idx]				,							'''tabby, tabby cat'''					)






import argparse
import struct
import unittest


class        __magic_name__	:





     """simple docstring"""



     def __init__(				self							:str      ,   snake_case							:bytes	):





        '''simple docstring'''




        A_       :					Dict        =      data

        # Initialize hash values
        A_       :					Union[str, Any]        =      [
            0x6a_09_e6_67,
            0xbb_67_ae_85,
            0x3c_6e_f3_72,
            0xa5_4f_f5_3a,
            0x51_0e_52_7f,
            0x9b_05_68_8c,
            0x1f_83_d9_ab,
            0x5b_e0_cd_19,
        ]

        # Initialize round constants
        A_       :					List[Any]        =      [
            0x42_8a_2f_98,
            0x71_37_44_91,
            0xb5_c0_fb_cf,
            0xe9_b5_db_a5,
            0x39_56_c2_5b,
            0x59_f1_11_f1,
            0x92_3f_82_a4,
            0xab_1c_5e_d5,
            0xd8_07_aa_98,
            0x12_83_5b_01,
            0x24_31_85_be,
            0x55_0c_7d_c3,
            0x72_be_5d_74,
            0x80_de_b1_fe,
            0x9b_dc_06_a7,
            0xc1_9b_f1_74,
            0xe4_9b_69_c1,
            0xef_be_47_86,
            0x0f_c1_9d_c6,
            0x24_0c_a1_cc,
            0x2d_e9_2c_6f,
            0x4a_74_84_aa,
            0x5c_b0_a9_dc,
            0x76_f9_88_da,
            0x98_3e_51_52,
            0xa8_31_c6_6d,
            0xb0_03_27_c8,
            0xbf_59_7f_c7,
            0xc6_e0_0b_f3,
            0xd5_a7_91_47,
            0x06_ca_63_51,
            0x14_29_29_67,
            0x27_b7_0a_85,
            0x2e_1b_21_38,
            0x4d_2c_6d_fc,
            0x53_38_0d_13,
            0x65_0a_73_54,
            0x76_6a_0a_bb,
            0x81_c2_c9_2e,
            0x92_72_2c_85,
            0xa2_bf_e8_a1,
            0xa8_1a_66_4b,
            0xc2_4b_8b_70,
            0xc7_6c_51_a3,
            0xd1_92_e8_19,
            0xd6_99_06_24,
            0xf4_0e_35_85,
            0x10_6a_a0_70,
            0x19_a4_c1_16,
            0x1e_37_6c_08,
            0x27_48_77_4c,
            0x34_b0_bc_b5,
            0x39_1c_0c_b3,
            0x4e_d8_aa_4a,
            0x5b_9c_ca_4f,
            0x68_2e_6f_f3,
            0x74_8f_82_ee,
            0x78_a5_63_6f,
            0x84_c8_78_14,
            0x8c_c7_02_08,
            0x90_be_ff_fa,
            0xa4_50_6c_eb,
            0xbe_f9_a3_f7,
            0xc6_71_78_f2,
        ]

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



     @staticmethod
     def     SCREAMING_SNAKE_CASE		(				snake_case							:bytes	):





        '''simple docstring'''




        A_       :					List[Any]        =      B"\x80" + (B"\x00" * (63 - (len(snake_case	) + 8) % 64))
        A_       :					str        =      struct.pack(">Q"      ,   (len(snake_case	) * 8)	)
        return data + padding + big_endian_integer



     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        A_       :					Tuple        =      [
            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
           A_       :					Dict        =      list(struct.unpack(">16L"      ,   snake_case	)	)
           # add 48 0-ed integers
           words += [0] * 48

           A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_       :					int        =      self.hashes

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

                 A_       :					Optional[int]        =      (
                     words[index - 16] + sa + words[index - 7] + sa
                 ) % 0x1_00_00_00_00

              # Compression
              A_       :					Dict        =      self.ror(snake_case      ,   6	) ^ self.ror(snake_case      ,   11	) ^ self.ror(snake_case      ,   25	)
              A_       :					int        =      (e & f) ^ ((~e & 0xff_ff_ff_ff) & g)
              A_       :					Optional[Any]        =      (
                  h + sa + ch + self.round_constants[index] + words[index]
              ) % 0x1_00_00_00_00
              A_       :					List[str]        =      self.ror(snake_case      ,   2	) ^ self.ror(snake_case      ,   13	) ^ self.ror(snake_case      ,   22	)
              A_       :					List[Any]        =      (a & b) ^ (a & c) ^ (b & c)
              A_       :					Dict        =      (sa + maj) % 0x1_00_00_00_00

              A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_   ,    A_       :					Optional[int]        =      (
                  g,
                  f,
                  e,
                  ((d + tempa) % 0x1_00_00_00_00),
                  c,
                  b,
                  a,
                  ((tempa + tempa) % 0x1_00_00_00_00),
              )

           A_       :					List[str]        =      [a, b, c, d, e, f, g, h]

           # Modify final values
           A_       :					List[str]        =      [
               ((element + mutated_hash_values[index]) % 0x1_00_00_00_00)
               for index, element in enumerate(self.hashes	)
           ]

        A_       :					Optional[int]        =      "".join([hex(snake_case	)[2:].zfill(8	) for value in self.hashes]	)





     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]      ,   snake_case							:int      ,   snake_case							:int	):





        '''simple docstring'''




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




class        __magic_name__	(				unittest.TestCase				):





     """simple docstring"""



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        import hashlib

        A_       :					int        =      bytes("Test String"      ,   "utf-8"	)
        self.assertEqual(SHAaaa(snake_case	).hash      ,   hashlib.shaaaa(snake_case	).hexdigest()	)




def   __snake_case    (       )			->    None:
   import doctest

   doctest.testmod()

   A_       :					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"						)

   A_       :					List[Any]        =      parser.parse_args()

   A_       :					List[Any]        =      args.input_string

   # hash input should be a bytestring
   if args.input_file:
      with open(args.input_file					,					"rb"						) as f:
         A_       :					Optional[Any]        =      f.read()
   else:
      A_       :					Any        =      bytes(_lowerCAmelCase					,					"utf-8"						)

   print(SHAaaa(_lowerCAmelCase						).hash						)


if __name__ == "__main__":
 main()
