'''simple docstring'''





from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import TFCvtForImageClassification, TFCvtModel
 from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    def       _UpperCamelCase    (       self )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       self.config_class(**self.inputs_dict )
         self.parent.assertTrue(hasattr(lowercase__    ,							'embed_dim' ) )
         self.parent.assertTrue(hasattr(lowercase__    ,							'num_heads' ) )






class 				UpperCAmelCase :




    '''simple docstring'''







    def __init__(       self    ,							lowercase__    ,							lowercase__=13    ,							lowercase__=64    ,							lowercase__=3    ,							lowercase__=[16, 48, 96]    ,							lowercase__=[1, 3, 6]    ,							lowercase__=[1, 2, 10]    ,							lowercase__=[7, 3, 3]    ,							lowercase__=[4, 2, 2]    ,							lowercase__=[2, 1, 1]    ,							lowercase__=[2, 2, 2]    ,							lowercase__=[False, False, True]    ,							lowercase__=[0.0, 0.0, 0.0]    ,							lowercase__=0.0_2    ,							lowercase__=1E-12    ,							lowercase__=True    ,							lowercase__=True    ,							lowercase__=2    ,							)							-> Optional[int]:
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       parent
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       batch_size
         SCREAMING_SNAKE_CASE					:			Dict    	=       image_size
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       patch_sizes
         SCREAMING_SNAKE_CASE					:			Dict    	=       patch_stride
         SCREAMING_SNAKE_CASE					:			int    	=       patch_padding
         SCREAMING_SNAKE_CASE					:			int    	=       is_training
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       use_labels
         SCREAMING_SNAKE_CASE					:			Any    	=       num_labels
         SCREAMING_SNAKE_CASE					:			List[str]    	=       num_channels
         SCREAMING_SNAKE_CASE					:			Any    	=       embed_dim
         SCREAMING_SNAKE_CASE					:			Any    	=       num_heads
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       stride_kv
         SCREAMING_SNAKE_CASE					:			List[str]    	=       depth
         SCREAMING_SNAKE_CASE					:			str    	=       cls_token
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       attention_drop_rate
         SCREAMING_SNAKE_CASE					:			List[str]    	=       initializer_range
         SCREAMING_SNAKE_CASE					:			Dict    	=       layer_norm_eps






    def       _UpperCamelCase    (       self )							-> str:
         SCREAMING_SNAKE_CASE					:			List[str]    	=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

         SCREAMING_SNAKE_CASE					:			Tuple    	=       None
         if self.use_labels:
              # create a random int32 tensor of given shape
              SCREAMING_SNAKE_CASE					:			List[Any]    	=       ids_tensor([self.batch_size]    ,							self.num_labels )

         SCREAMING_SNAKE_CASE					:			Dict    	=       self.get_config()
         return config, pixel_values, labels






    def       _UpperCamelCase    (       self )							-> int:
         return CvtConfig(
             image_size=self.image_size    ,							num_labels=self.num_labels    ,							num_channels=self.num_channels    ,							embed_dim=self.embed_dim    ,							num_heads=self.num_heads    ,							patch_sizes=self.patch_sizes    ,							patch_padding=self.patch_padding    ,							patch_stride=self.patch_stride    ,							stride_kv=self.stride_kv    ,							depth=self.depth    ,							cls_token=self.cls_token    ,							attention_drop_rate=self.attention_drop_rate    ,							initializer_range=self.initializer_range    ,							)






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE					:			Dict    	=       TFCvtModel(config=lowercase__ )
         SCREAMING_SNAKE_CASE					:			List[str]    	=       model(lowercase__    ,							training=lowercase__ )
         SCREAMING_SNAKE_CASE					:			Tuple    	=       (self.image_size, self.image_size)
         SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			List[str]    	=       image_size[0], image_size[1]
         for i in range(len(self.depth ) ):
              SCREAMING_SNAKE_CASE					:			Optional[int]    	=       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
              SCREAMING_SNAKE_CASE					:			Dict    	=       floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
         self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.embed_dim[-1], height, width) )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ )							-> List[Any]:
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       self.num_labels
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       TFCvtForImageClassification(lowercase__ )
         SCREAMING_SNAKE_CASE					:			int    	=       model(lowercase__    ,							labels=lowercase__    ,							training=lowercase__ )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_labels) )






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






@require_tf
class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE   ,    _SCREAMING_SNAKE_CASE   ,    unittest.TestCase ):




    '''simple docstring'''







    snake_case__							:   str							=						(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
    snake_case__							:   str							=						(
        {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
        if is_tf_available()
        else {}
    )
    snake_case__							:   Dict							=						False
    snake_case__							:   str							=						False
    snake_case__							:   Optional[int]							=						False
    snake_case__							:   str							=						False
    snake_case__							:   Optional[Any]							=						False






    def       _UpperCamelCase    (       self )							-> int:
         SCREAMING_SNAKE_CASE					:			int    	=       TFCvtModelTester(self )
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       TFCvtConfigTester(self    ,							config_class=lowercase__    ,							has_text_modality=lowercase__    ,							hidden_size=37 )






    def       _UpperCamelCase    (       self )							-> Tuple:
         self.config_tester.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()






    @unittest.skip(reason='Cvt does not output attentions' )
    def       _UpperCamelCase    (       self )							-> List[str]:
         pass






    @unittest.skip(reason='Cvt does not use inputs_embeds' )
    def       _UpperCamelCase    (       self )							-> Any:
         pass






    @unittest.skip(reason='Cvt does not support input and output embeddings' )
    def       _UpperCamelCase    (       self )							-> int:
         pass






    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0    ,							reason='TF does not support backprop for grouped convolutions on CPU.'    ,							)
    def       _UpperCamelCase    (       self )							-> Dict:
         super().test_dataset_conversion()






    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0    ,							reason='TF does not support backprop for grouped convolutions on CPU.'    ,							)
    @slow
    def       _UpperCamelCase    (       self )							-> Any:
         super().test_keras_fit()






    @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' )
    def       _UpperCamelCase    (       self )							-> Any:
         SCREAMING_SNAKE_CASE					:			List[str]    	=       tf.keras.mixed_precision.Policy('mixed_float16' )
         tf.keras.mixed_precision.set_global_policy(lowercase__ )
         super().test_keras_fit()
         tf.keras.mixed_precision.set_global_policy('float32' )






    def       _UpperCamelCase    (       self )							-> int:
         SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			Tuple    	=       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE					:			Any    	=       model_class(lowercase__ )
              SCREAMING_SNAKE_CASE					:			Dict    	=       inspect.signature(model.call )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       [*signature.parameters.keys()]

              SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       ['pixel_values']
              self.assertListEqual(arg_names[:1]    ,							lowercase__ )






    def       _UpperCamelCase    (       self )							-> str:
         def check_hidden_states_output(lowercase__    ,							lowercase__    ,							lowercase__ ):
              SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       model_class(lowercase__ )

              SCREAMING_SNAKE_CASE					:			Any    	=       model(**self._prepare_for_class(lowercase__    ,							lowercase__ ) )
              SCREAMING_SNAKE_CASE					:			str    	=       outputs.hidden_states

              SCREAMING_SNAKE_CASE					:			int    	=       len(self.model_tester.depth )
              self.assertEqual(len(lowercase__ )    ,							lowercase__ )

              # verify the first hidden states (first block)
              self.assertListEqual(
                  list(hidden_states[0].shape[-3:] )    ,							[
                      self.model_tester.embed_dim[0],
                      self.model_tester.image_size // 4,
                      self.model_tester.image_size // 4,
                  ]    ,							)

         SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			Tuple    	=       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       True
              check_hidden_states_output(lowercase__    ,							lowercase__    ,							lowercase__ )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE					:			List[Any]    	=       True

              check_hidden_states_output(lowercase__    ,							lowercase__    ,							lowercase__ )






    def       _UpperCamelCase    (       self )							-> Tuple:
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowercase__ )






    def       _UpperCamelCase    (       self )							-> Dict:
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowercase__ )






    @slow
    def       _UpperCamelCase    (       self )							-> Any:
         for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE					:			Any    	=       TFCvtModel.from_pretrained(lowercase__ )
              self.assertIsNotNone(lowercase__ )






def     __lowerCAmelCase						(       )      ->	Tuple:





     '''simple docstring'''





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






@require_tf
@require_vision
class 				UpperCAmelCase (       unittest.TestCase ):




    '''simple docstring'''







    @cached_property
    def       _UpperCamelCase    (       self )							-> List[Any]:
         return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )






    @slow
    def       _UpperCamelCase    (       self )							-> List[str]:
         SCREAMING_SNAKE_CASE					:			List[str]    	=       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )

         SCREAMING_SNAKE_CASE					:			str    	=       self.default_image_processor
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       prepare_img()
         SCREAMING_SNAKE_CASE					:			List[str]    	=       image_processor(images=lowercase__    ,							return_tensors='tf' )

         # forward pass
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       model(**lowercase__ )

         # verify the logits
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       tf.TensorShape((1, 1_000) )
         self.assertEqual(outputs.logits.shape    ,							lowercase__ )

         SCREAMING_SNAKE_CASE					:			Dict    	=       tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0] )
         self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,							lowercase__    ,							atol=1E-4 ) )




'''simple docstring'''





import argparse
import struct
import unittest






class 				UpperCAmelCase :




    '''simple docstring'''







    def __init__(       self    ,							lowercase__ )							-> None:
         SCREAMING_SNAKE_CASE					:			List[str]    	=       data

         # Initialize hash values
         SCREAMING_SNAKE_CASE					:			str    	=       [
             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
         SCREAMING_SNAKE_CASE					:			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,
         ]

         SCREAMING_SNAKE_CASE					:			List[Any]    	=       self.preprocessing(self.data )
         self.final_hash()






    @staticmethod
    def       _UpperCamelCase    (       lowercase__ )							-> bytes:
         SCREAMING_SNAKE_CASE					:			str    	=       B'\x80' + (B'\x00' * (63 - (len(lowercase__ ) + 8) % 64))
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       struct.pack('>Q'    ,							(len(lowercase__ ) * 8) )
         return data + padding + big_endian_integer






    def       _UpperCamelCase    (       self )							-> None:
         # Convert into blocks of 64 bytes
         SCREAMING_SNAKE_CASE					:			Dict    	=       [
             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
              SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       list(struct.unpack('>16L'    ,							lowercase__ ) )
              # add 48 0-ed integers
              words += [0] * 48

              SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			Dict    	=       self.hashes

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

                        SCREAMING_SNAKE_CASE					:			Tuple    	=       (
                            words[index - 16] + sa + words[index - 7] + sa
                        ) % 0X1_00_00_00_00

                   # Compression
                   SCREAMING_SNAKE_CASE					:			Any    	=       self.ror(lowercase__    ,							6 ) ^ self.ror(lowercase__    ,							11 ) ^ self.ror(lowercase__    ,							25 )
                   SCREAMING_SNAKE_CASE					:			Any    	=       (e & f) ^ ((~e & 0XFF_FF_FF_FF) & g)
                   SCREAMING_SNAKE_CASE					:			str    	=       (
                       h + sa + ch + self.round_constants[index] + words[index]
                   ) % 0X1_00_00_00_00
                   SCREAMING_SNAKE_CASE					:			Any    	=       self.ror(lowercase__    ,							2 ) ^ self.ror(lowercase__    ,							13 ) ^ self.ror(lowercase__    ,							22 )
                   SCREAMING_SNAKE_CASE					:			str    	=       (a & b) ^ (a & c) ^ (b & c)
                   SCREAMING_SNAKE_CASE					:			Tuple    	=       (sa + maj) % 0X1_00_00_00_00

                   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			List[Any]    	=       (
                       g,
                       f,
                       e,
                       ((d + tempa) % 0X1_00_00_00_00),
                       c,
                       b,
                       a,
                       ((tempa + tempa) % 0X1_00_00_00_00),
                   )

              SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       [a, b, c, d, e, f, g, h]

              # Modify final values
              SCREAMING_SNAKE_CASE					:			Tuple    	=       [
                  ((element + mutated_hash_values[index]) % 0X1_00_00_00_00)
                  for index, element in enumerate(self.hashes )
              ]

         SCREAMING_SNAKE_CASE					:			Tuple    	=       ''.join([hex(lowercase__ )[2:].zfill(8 ) for value in self.hashes] )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__ )							-> int:
         return 0XFF_FF_FF_FF & (value << (32 - rotations)) | (value >> rotations)






class 				UpperCAmelCase (       unittest.TestCase ):




    '''simple docstring'''







    def       _UpperCamelCase    (       self )							-> None:
         import hashlib

         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       bytes('Test String'    ,							'utf-8' )
         self.assertEqual(SHAaaa(lowercase__ ).hash    ,							hashlib.shaaaa(lowercase__ ).hexdigest() )






def     __lowerCAmelCase						(       )      ->	None:





     '''simple docstring'''





     import doctest

     doctest.testmod()

     SCREAMING_SNAKE_CASE					:			List[str]    	=       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'		)

     SCREAMING_SNAKE_CASE					:			Tuple    	=       parser.parse_args()

     SCREAMING_SNAKE_CASE					:			List[Any]    	=       args.input_string

     # hash input should be a bytestring
     if args.input_file:
          with open(args.input_file       ,      'rb'		) as f:
               SCREAMING_SNAKE_CASE					:			List[Any]    	=       f.read()
     else:
          SCREAMING_SNAKE_CASE					:			Any    	=       bytes(a_       ,      'utf-8'		)

     print(SHAaaa(a_		).hash		)


if __name__ == "__main__":
 main()



