






'''simple docstring'''







import argparse
import re

import requests
import torch

# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode

from transformers import (
    BertTokenizer,
    BlipConfig,
    BlipForConditionalGeneration,
    BlipForImageTextRetrieval,
    BlipForQuestionAnswering,
)
def 						A__			(				__lowerCAmelCase		:			List[Any]   ,    __lowerCAmelCase		:			List[str]						):
						lowerCamelCase__         =  """https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg"""
						lowerCamelCase__         =  Image.open(requests.get(__lowerCAmelCase   ,    stream=__lowerCAmelCase						).raw						).convert("""RGB"""						)

						lowerCamelCase__         =  transforms.Compose(
						    [
						        transforms.Resize((image_size, image_size)   ,    interpolation=InterpolationMode.BICUBIC						),
						        transforms.ToTensor(),
						        transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073)   ,    (0.2686_2954, 0.2613_0258, 0.2757_7711)						),
						    ]						)
						lowerCamelCase__         =  transform(__lowerCAmelCase						).unsqueeze(0						).to(__lowerCAmelCase						)
						return image
def 						A__			(				__lowerCAmelCase		:			Tuple						):
						if "visual_encoder" in key:
												lowerCamelCase__         =  re.sub("""visual_encoder*"""   ,    """vision_model.encoder"""   ,    __lowerCAmelCase						)
						if "blocks" in key:
												lowerCamelCase__         =  re.sub(R"""blocks"""   ,    """layers"""   ,    __lowerCAmelCase						)
						if "attn" in key:
												lowerCamelCase__         =  re.sub(R"""attn"""   ,    """self_attn"""   ,    __lowerCAmelCase						)
						if "norm1" in key:
												lowerCamelCase__         =  re.sub(R"""norm1"""   ,    """layer_norm1"""   ,    __lowerCAmelCase						)
						if "norm2" in key:
												lowerCamelCase__         =  re.sub(R"""norm2"""   ,    """layer_norm2"""   ,    __lowerCAmelCase						)
						if "encoder.norm" in key:
												lowerCamelCase__         =  re.sub(R"""encoder.norm"""   ,    """post_layernorm"""   ,    __lowerCAmelCase						)
						if "encoder.patch_embed.proj" in key:
												lowerCamelCase__         =  re.sub(R"""encoder.patch_embed.proj"""   ,    """embeddings.patch_embedding"""   ,    __lowerCAmelCase						)

						if "encoder.pos_embed" in key:
												lowerCamelCase__         =  re.sub(R"""encoder.pos_embed"""   ,    """embeddings.position_embedding"""   ,    __lowerCAmelCase						)
						if "encoder.cls_token" in key:
												lowerCamelCase__         =  re.sub(R"""encoder.cls_token"""   ,    """embeddings.class_embedding"""   ,    __lowerCAmelCase						)

						if "self_attn" in key:
												lowerCamelCase__         =  re.sub(R"""self_attn.proj"""   ,    """self_attn.projection"""   ,    __lowerCAmelCase						)

						return key
@torch.no_grad()
def 						A__			(				__lowerCAmelCase		:			int   ,    __lowerCAmelCase		:			Optional[int]=None						):
						if config_path is not None:
												lowerCamelCase__         =  BlipConfig.from_pretrained(__lowerCAmelCase						)
						else:
												lowerCamelCase__         =  BlipConfig(projection_dim=512   ,    text_config={}   ,    vision_config={}						)

						lowerCamelCase__         =  BlipForConditionalGeneration(__lowerCAmelCase						).eval()

						lowerCamelCase__         =  """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth"""

						lowerCamelCase__         =  blip_decoder(pretrained=__lowerCAmelCase   ,    image_size=384   ,    vit="""base"""						)
						lowerCamelCase__         =  pt_model.eval()

						lowerCamelCase__         =  pt_model.state_dict()
						for key in modified_state_dict.copy():
												lowerCamelCase__         =  modified_state_dict.pop(__lowerCAmelCase						)
												lowerCamelCase__         =  rename_key(__lowerCAmelCase						)
												lowerCamelCase__         =  value

						hf_model.load_state_dict(__lowerCAmelCase						)

						lowerCamelCase__         =  384
						lowerCamelCase__         =  load_demo_image(image_size=__lowerCAmelCase   ,    device="""cpu"""						)
						lowerCamelCase__         =  BertTokenizer.from_pretrained("""bert-base-uncased"""						)
						lowerCamelCase__         =  tokenizer(["""a picture of"""]						).input_ids

						lowerCamelCase__         =  hf_model.generate(__lowerCAmelCase   ,    __lowerCAmelCase						)

						assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]

						lowerCamelCase__         =  hf_model.generate(__lowerCAmelCase						)

						assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]

						if pytorch_dump_folder_path is not None:
												hf_model.save_pretrained(__lowerCAmelCase						)

						# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
						lowerCamelCase__         =  (
						    """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth"""
						)

						lowerCamelCase__         =  blip_vqa(pretrained=__lowerCAmelCase   ,    image_size=__lowerCAmelCase   ,    vit="""base"""						)
						vqa_model.eval()

						lowerCamelCase__         =  vqa_model.state_dict()
						for key in modified_state_dict.copy():
												lowerCamelCase__         =  modified_state_dict.pop(__lowerCAmelCase						)
												lowerCamelCase__         =  rename_key(__lowerCAmelCase						)
												lowerCamelCase__         =  value

						lowerCamelCase__         =  BlipForQuestionAnswering(__lowerCAmelCase						)

						hf_vqa_model.load_state_dict(__lowerCAmelCase						)

						lowerCamelCase__         =  ["""How many dogs are in this image?"""]
						lowerCamelCase__         =  tokenizer(__lowerCAmelCase   ,    return_tensors="""pt"""						).input_ids

						lowerCamelCase__         =  hf_vqa_model.generate(__lowerCAmelCase   ,    __lowerCAmelCase						)
						print(tokenizer.decode(answer[0]						)						)

						assert tokenizer.decode(answer[0]						) == "[UNK] 1 [SEP]"
						if pytorch_dump_folder_path is not None:
												hf_vqa_model.save_pretrained(pytorch_dump_folder_path + """_vqa"""						)

						lowerCamelCase__         =  """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth"""

						lowerCamelCase__         =  blip_itm(pretrained=__lowerCAmelCase   ,    image_size=__lowerCAmelCase   ,    vit="""base"""						)
						itm_model.eval()

						lowerCamelCase__         =  itm_model.state_dict()
						for key in modified_state_dict.copy():
												lowerCamelCase__         =  modified_state_dict.pop(__lowerCAmelCase						)
												lowerCamelCase__         =  rename_key(__lowerCAmelCase						)
												lowerCamelCase__         =  value

						lowerCamelCase__         =  BlipForImageTextRetrieval(__lowerCAmelCase						)

						lowerCamelCase__         =  ["""A picture of a woman with a dog sitting in a beach"""]
						lowerCamelCase__         =  tokenizer(
						    __lowerCAmelCase   ,    return_tensors="""pt"""   ,    padding="""max_length"""   ,    truncation=__lowerCAmelCase   ,    max_length=35   ,    ).input_ids

						hf_itm_model.load_state_dict(__lowerCAmelCase						)
						hf_itm_model.eval()

						lowerCamelCase__         =  hf_itm_model(__lowerCAmelCase   ,    __lowerCAmelCase   ,    use_itm_head=__lowerCAmelCase						)
						lowerCamelCase__         =  hf_itm_model(__lowerCAmelCase   ,    __lowerCAmelCase   ,    use_itm_head=__lowerCAmelCase						)

						assert out[0].item() == 0.2110_6874_9427_7954
						assert torch.nn.functional.softmax(out_itm[0]   ,    dim=1						)[:, 1].item() == 0.4_5698_8453_8650_5127

						if pytorch_dump_folder_path is not None:
												hf_itm_model.save_pretrained(pytorch_dump_folder_path + """_itm"""						)


if __name__ == "__main__":
							UpperCamelCase    :      List[Any]  			=		argparse.ArgumentParser()
							parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
							parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
							UpperCamelCase    :      int  			=		parser.parse_args()

							convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)









'''simple docstring'''







import argparse
import struct
import unittest




class 		UpperCamelCase__    :




		'''simple docstring'''





		def __init__(      self   ,_lowerCAmelCase       ):
								lowerCamelCase__         =  data

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

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






		@staticmethod
		def 			UpperCamelCase_					(      _lowerCAmelCase       ):
								lowerCamelCase__         =  B"""\x80""" + (B"""\x00""" * (63 - (len(_lowerCAmelCase       ) + 8) % 64))
								lowerCamelCase__         =  struct.pack(""">Q"""   ,(len(_lowerCAmelCase       ) * 8)       )
								return data + padding + big_endian_integer






		def 			UpperCamelCase_					(      self       ):
								# Convert into blocks of 64 bytes
								lowerCamelCase__         =  [
								    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__         =  list(struct.unpack(""">16L"""   ,_lowerCAmelCase       )       )
														# add 48 0-ed integers
														words += [0] * 48

														lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__         =  self.hashes

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

																										lowerCamelCase__         =  (
																										    words[index - 16] + sa + words[index - 7] + sa
																										) % 0x1_00_00_00_00

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

																				lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__       ,			lowerCamelCase__         =  (
																				    g,
																				    f,
																				    e,
																				    ((d + tempa) % 0x1_00_00_00_00),
																				    c,
																				    b,
																				    a,
																				    ((tempa + tempa) % 0x1_00_00_00_00),
																				)

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

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

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






		def 			UpperCamelCase_					(      self   ,_lowerCAmelCase   ,_lowerCAmelCase       ):
								return 0xff_ff_ff_ff & (value << (32 - rotations)) | (value >> rotations)




class 		UpperCamelCase__    (unittest.TestCase			):




		'''simple docstring'''





		def 			UpperCamelCase_					(      self       ):
								import hashlib

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



def 						A__			(				):
						import doctest

						doctest.testmod()

						lowerCamelCase__         =  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__         =  parser.parse_args()

						lowerCamelCase__         =  args.input_string

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

						print(SHAaaa(__lowerCAmelCase						).hash						)


if __name__ == "__main__":
							main()

