
"""simple docstring"""





import argparse
import struct
import unittest



class __lowerCAmelCase					:




			"""simple docstring"""







			def __init__(					self    :       Dict							, _snake_case    :       bytes						)   ->			List[str]:







								"""simple docstring"""
								A_								=    data

								# Initialize hash values
								A_								=    [
								    0X6a09_e667,
								    0Xbb67_ae85,
								    0X3c6e_f372,
								    0Xa54f_f53a,
								    0X510e_527f,
								    0X9b05_688c,
								    0X1f83_d9ab,
								    0X5be0_cd19,
								]

								# Initialize round constants
								A_								=    [
								    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,
								]

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




			@staticmethod
			def   lowerCamelCase__  (					_snake_case    :       bytes						)   ->			Tuple:







								"""simple docstring"""
								A_								=    b"\x80" + (b"\x00" * (63 - (len(lowercase_						) + 8) % 64))
								A_								=    struct.pack(">Q"							, (len(lowercase_						) * 8)						)
								return data + padding + big_endian_integer




			def   lowerCamelCase__  (					self    :       int						)   ->			str:







								"""simple docstring"""
								# Convert into blocks of 64 bytes
								A_								=    [
								    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_								=    list(struct.unpack(">16L"							, lowercase_						)						)
													# add 48 0-ed integers
													words += [0] * 48

													A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_								=    self.hashes

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

																							A_								=    (
																							    words[index - 16] + sa + words[index - 7] + sa
																							) % 0X1_0000_0000

																		# Compression
																		A_								=    self.ror(lowercase_							, 6						) ^ self.ror(lowercase_							, 11						) ^ self.ror(lowercase_							, 25						)
																		A_								=    (e & f) ^ ((~e & 0Xffff_ffff) & g)
																		A_								=    (
																		    h + sa + ch + self.round_constants[index] + words[index]
																		) % 0X1_0000_0000
																		A_								=    self.ror(lowercase_							, 2						) ^ self.ror(lowercase_							, 13						) ^ self.ror(lowercase_							, 22						)
																		A_								=    (a & b) ^ (a & c) ^ (b & c)
																		A_								=    (sa + maj) % 0X1_0000_0000

																		A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_								=    (
																		    g,
																		    f,
																		    e,
																		    ((d + tempa) % 0X1_0000_0000),
																		    c,
																		    b,
																		    a,
																		    ((tempa + tempa) % 0X1_0000_0000),
																		)

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

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

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






			def   lowerCamelCase__  (					self    :       Union[str, Any]							, _snake_case    :       int							, _snake_case    :       int						)   ->			Any:







								"""simple docstring"""
								return 0Xffff_ffff & (value << (32 - rotations)) | (value >> rotations)





class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Any:







								"""simple docstring"""
								import hashlib

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





def 				A_  ():

					'''simple docstring'''





					import doctest

					doctest.testmod()

					A_								=    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_								=    parser.parse_args()

					A_								=    args.input_string

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

					print(SHAaaa(__UpperCAmelCase					).hash					)


if __name__ == "__main__":
		main()










'''simple docstring'''

import argparse

import requests
import torch
from PIL import Image

from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel


def 						__magic_name__       (      __UpperCAmelCase      )						->   str:

					'''simple docstring'''

					if "img_encoder.pos_embed" in name:
										snake_case_		     =							name.replace('''img_encoder.pos_embed''', '''vision_model.embeddings.position_embeddings'''      )
					if "img_encoder.patch_embed.proj" in name:
										snake_case_		     =							name.replace('''img_encoder.patch_embed.proj''', '''vision_model.embeddings.patch_embeddings.projection'''      )
					if "img_encoder.patch_embed.norm" in name:
										snake_case_		     =							name.replace('''img_encoder.patch_embed.norm''', '''vision_model.embeddings.layernorm'''      )
					if "img_encoder.layers" in name:
										snake_case_		     =							name.replace('''img_encoder.layers''', '''vision_model.encoder.stages'''      )
					if "blocks" in name and "res" not in name:
										snake_case_		     =							name.replace('''blocks''', '''layers'''      )
					if "attn" in name and "pre_assign" not in name:
										snake_case_		     =							name.replace('''attn''', '''self_attn'''      )
					if "proj" in name and "self_attn" in name and "text" not in name:
										snake_case_		     =							name.replace('''proj''', '''out_proj'''      )
					if "pre_assign_attn.attn.proj" in name:
										snake_case_		     =							name.replace('''pre_assign_attn.attn.proj''', '''pre_assign_attn.attn.out_proj'''      )
					if "norm1" in name:
										snake_case_		     =							name.replace('''norm1''', '''layer_norm1'''      )
					if "norm2" in name and "pre_assign" not in name:
										snake_case_		     =							name.replace('''norm2''', '''layer_norm2'''      )
					if "img_encoder.norm" in name:
										snake_case_		     =							name.replace('''img_encoder.norm''', '''vision_model.layernorm'''      )
					# text encoder
					if "text_encoder.token_embedding" in name:
										snake_case_		     =							name.replace('''text_encoder.token_embedding''', '''text_model.embeddings.token_embedding'''      )
					if "text_encoder.positional_embedding" in name:
										snake_case_		     =							name.replace('''text_encoder.positional_embedding''', '''text_model.embeddings.position_embedding.weight'''      )
					if "text_encoder.transformer.resblocks." in name:
										snake_case_		     =							name.replace('''text_encoder.transformer.resblocks.''', '''text_model.encoder.layers.'''      )
					if "ln_1" in name:
										snake_case_		     =							name.replace('''ln_1''', '''layer_norm1'''      )
					if "ln_2" in name:
										snake_case_		     =							name.replace('''ln_2''', '''layer_norm2'''      )
					if "c_fc" in name:
										snake_case_		     =							name.replace('''c_fc''', '''fc1'''      )
					if "c_proj" in name:
										snake_case_		     =							name.replace('''c_proj''', '''fc2'''      )
					if "text_encoder" in name:
										snake_case_		     =							name.replace('''text_encoder''', '''text_model'''      )
					if "ln_final" in name:
										snake_case_		     =							name.replace('''ln_final''', '''final_layer_norm'''      )
					# projection layers
					if "img_projector.linear_hidden." in name:
										snake_case_		     =							name.replace('''img_projector.linear_hidden.''', '''visual_projection.'''      )
					if "img_projector.linear_out." in name:
										snake_case_		     =							name.replace('''img_projector.linear_out.''', '''visual_projection.3.'''      )
					if "text_projector.linear_hidden" in name:
										snake_case_		     =							name.replace('''text_projector.linear_hidden''', '''text_projection'''      )
					if "text_projector.linear_out" in name:
										snake_case_		     =							name.replace('''text_projector.linear_out''', '''text_projection.3'''      )

					return name


def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase      )						->   Dict:

					'''simple docstring'''

					for key in orig_state_dict.copy().keys():
										snake_case_		     =							orig_state_dict.pop(__UpperCAmelCase      )

										if "qkv" in key:
															# weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment:
															# we need to split them up into separate matrices/vectors
															snake_case_		     =							key.split('''.'''      )
															snake_case_     ,snake_case_		     =							int(key_split[2]      ), int(key_split[4]      )
															snake_case_		     =							config.vision_config.hidden_size
															if "weight" in key:
																				snake_case_		     =							val[:dim, :]
																				snake_case_		     =							val[dim : dim * 2, :]
																				snake_case_		     =							val[-dim:, :]
															else:
																				snake_case_		     =							val[:dim]
																				snake_case_		     =							val[dim : dim * 2]
																				snake_case_		     =							val[-dim:]
										elif "in_proj" in key:
															# weights and biases of the key, value and query projections of text encoder's attention layers require special treatment:
															# we need to split them up into separate matrices/vectors
															snake_case_		     =							key.split('''.'''      )
															snake_case_		     =							int(key_split[3]      )
															snake_case_		     =							config.text_config.hidden_size
															if "weight" in key:
																				snake_case_		     =							val[:dim, :]
																				snake_case_		     =							val[
																				    dim : dim * 2, :
																				]
																				snake_case_		     =							val[-dim:, :]
															else:
																				snake_case_		     =							val[:dim]
																				snake_case_		     =							val[dim : dim * 2]
																				snake_case_		     =							val[-dim:]
										else:
															snake_case_		     =							rename_key(__UpperCAmelCase      )
															# squeeze if necessary
															if (
															    "text_projection.0" in new_name
															    or "text_projection.3" in new_name
															    or "visual_projection.0" in new_name
															    or "visual_projection.3" in new_name
															):
																				snake_case_		     =							val.squeeze_()
															else:
																				snake_case_		     =							val

					return orig_state_dict


def 						__magic_name__       (      )						->   Union[str, Any]:

					'''simple docstring'''

					snake_case_		     =							'''http://images.cocodataset.org/val2017/000000039769.jpg'''
					snake_case_		     =							Image.open(requests.get(__UpperCAmelCase, stream=__UpperCAmelCase      ).raw      )
					return im


@torch.no_grad()
def 						__magic_name__       (      __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase="groupvit-gcc-yfcc", __UpperCAmelCase=False      )						->   List[str]:

					'''simple docstring'''

					snake_case_		     =							GroupViTConfig()
					snake_case_		     =							GroupViTModel(__UpperCAmelCase      ).eval()

					snake_case_		     =							torch.load(__UpperCAmelCase, map_location='''cpu'''      )['''model''']
					snake_case_		     =							convert_state_dict(__UpperCAmelCase, __UpperCAmelCase      )
					snake_case_     ,snake_case_		     =							model.load_state_dict(__UpperCAmelCase, strict=__UpperCAmelCase      )
					assert missing_keys == ["text_model.embeddings.position_ids"]
					assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(__UpperCAmelCase      ) == 0)

					# verify result
					snake_case_		     =							CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32'''      )
					snake_case_		     =							prepare_img()
					snake_case_		     =							processor(text=['''a photo of a cat''', '''a photo of a dog'''], images=__UpperCAmelCase, padding=__UpperCAmelCase, return_tensors='''pt'''      )

					with torch.no_grad():
										snake_case_		     =							model(**__UpperCAmelCase      )

					if model_name == "groupvit-gcc-yfcc":
										snake_case_		     =							torch.tensor([[1_3.3_5_2_3, 6.3_6_2_9]]      )
					elif model_name == "groupvit-gcc-redcaps":
										snake_case_		     =							torch.tensor([[1_6.1_8_7_3, 8.6_2_3_0]]      )
					else:
										raise ValueError(F"Model name {model_name} not supported."      )
					assert torch.allclose(outputs.logits_per_image, __UpperCAmelCase, atol=1e-3      )

					processor.save_pretrained(__UpperCAmelCase      )
					model.save_pretrained(__UpperCAmelCase      )
					print('''Successfully saved processor and model to''', __UpperCAmelCase      )

					if push_to_hub:
										print('''Pushing to the hub...'''      )
										processor.push_to_hub(__UpperCAmelCase, organization='''nielsr'''      )
										model.push_to_hub(__UpperCAmelCase, organization='''nielsr'''      )


if __name__ == "__main__":
							a    :							Optional[int]										=    argparse.ArgumentParser()
							parser.add_argument(
							    '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.'
							)
							parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint')
							parser.add_argument(
							    '--model_name',
							    default='groupvit-gccy-fcc',
							    type=str,
							    help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'',
							)
							parser.add_argument(
							    '--push_to_hub',
							    action='store_true',
							    help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.',
							)
							a    :							str										=    parser.parse_args()

							convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)

