



'''simple docstring'''

import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


logging.set_verbosity_info()
__lowerCAmelCase						      =       logging.get_logger(__name__)



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_=False  )      ->				Any:
		_a					:				Union[str, Any]				=							[]
		for i in range(config.num_hidden_layers  ):
				# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
				rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""")  )
				rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""")  )
				rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""")  )
				rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""")  )
				rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""")  )
				rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""")  )
				rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""")  )
				rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""")  )
				rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""")  )
				rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""")  )

		# projection layer + position embeddings
		rename_keys.extend(
		    [
		        ('cls_token', 'vit.embeddings.cls_token'),
		        ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'),
		        ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'),
		        ('pos_embed', 'vit.embeddings.position_embeddings'),
		    ]  )

		if base_model:
				# layernorm + pooler
				rename_keys.extend(
				    [
				        ('norm.weight', 'layernorm.weight'),
				        ('norm.bias', 'layernorm.bias'),
				    ]  )

				# if just the base model, we should remove "vit" from all keys that start with "vit"
				_a					:				Tuple				=							[(pair[0], pair[1][4:]) if pair[1].startswith('vit'  ) else pair for pair in rename_keys]
		else:
				# layernorm + classification head
				rename_keys.extend(
				    [
				        ('norm.weight', 'vit.layernorm.weight'),
				        ('norm.bias', 'vit.layernorm.bias'),
				        ('head.weight', 'classifier.weight'),
				        ('head.bias', 'classifier.bias'),
				    ]  )

		return rename_keys



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_=False  )      ->				str:
		for i in range(config.num_hidden_layers  ):
				if base_model:
						_a					:				Optional[Any]				=							''
				else:
						_a					:				Optional[int]				=							'vit.'
				# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
				_a					:				Union[str, Any]				=							state_dict.pop(f"""blocks.{i}.attn.qkv.weight"""  )
				_a					:				Tuple				=							state_dict.pop(f"""blocks.{i}.attn.qkv.bias"""  )
				# next, add query, keys and values (in that order) to the state dict
				_a					:				Any				=							in_proj_weight[
				    : config.hidden_size, :
				]
				_a					:				Optional[Any]				=							in_proj_bias[: config.hidden_size]
				_a					:				Any				=							in_proj_weight[
				    config.hidden_size : config.hidden_size * 2, :
				]
				_a					:				str				=							in_proj_bias[
				    config.hidden_size : config.hidden_size * 2
				]
				_a					:				int				=							in_proj_weight[
				    -config.hidden_size :, :
				]
				_a					:				List[str]				=							in_proj_bias[-config.hidden_size :]



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Dict:
		_a					:				int				=							['head.weight', 'head.bias']
		for k in ignore_keys:
				state_dict.pop(lowerCAmelCase_						,      lowerCAmelCase_  )



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )      ->				Optional[int]:
		_a					:				Dict				=							dct.pop(lowerCAmelCase_  )
		_a					:				Union[str, Any]				=							val



def 					__lowerCamelCase					(				)      ->				Optional[int]:
		_a					:				List[str]				=							'http://images.cocodataset.org/val2017/000000039769.jpg'
		_a					:				Union[str, Any]				=							Image.open(requests.get(lowerCAmelCase_						,      stream=lowerCAmelCase_  ).raw  )
		return im



@torch.no_grad()
def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_=True  )      ->				Dict:
		_a					:				int				=							ViTConfig()
		# patch_size
		if model_name[-1] == "8":
				_a					:				Tuple				=							8
		# set labels if required
		if not base_model:
				_a					:				List[Any]				=							1000
				_a					:				List[str]				=							'huggingface/label-files'
				_a					:				Optional[int]				=							'imagenet-1k-id2label.json'
				_a					:				Union[str, Any]				=							json.load(open(hf_hub_download(lowerCAmelCase_						,      lowerCAmelCase_						,      repo_type='dataset'  )						,      'r'  )  )
				_a					:				List[Any]				=							{int(lowerCAmelCase_  ): v for k, v in idalabel.items()}
				_a					:				Union[str, Any]				=							idalabel
				_a					:				Optional[Any]				=							{v: k for k, v in idalabel.items()}
		# size of the architecture
		if model_name in ["dino_vits8", "dino_vits16"]:
				_a					:				List[str]				=							384
				_a					:				str				=							1536
				_a					:				Optional[Any]				=							12
				_a					:				Optional[Any]				=							6

		# load original model from torch hub
		_a					:				Optional[Any]				=							torch.hub.load('facebookresearch/dino:main'						,      lowerCAmelCase_  )
		original_model.eval()

		# load state_dict of original model, remove and rename some keys
		_a					:				Optional[int]				=							original_model.state_dict()
		if base_model:
				remove_classification_head_(lowerCAmelCase_  )
		_a					:				Optional[Any]				=							create_rename_keys(lowerCAmelCase_						,      base_model=lowerCAmelCase_  )
		for src, dest in rename_keys:
				rename_key(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )
		read_in_q_k_v(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )

		# load HuggingFace model
		if base_model:
				_a					:				List[Any]				=							ViTModel(lowerCAmelCase_						,      add_pooling_layer=lowerCAmelCase_  ).eval()
		else:
				_a					:				Union[str, Any]				=							ViTForImageClassification(lowerCAmelCase_  ).eval()
		model.load_state_dict(lowerCAmelCase_  )

		# Check outputs on an image, prepared by ViTImageProcessor
		_a					:				Tuple				=							ViTImageProcessor()
		_a					:				Any				=							image_processor(images=prepare_img()						,      return_tensors='pt'  )
		_a					:				int				=							encoding['pixel_values']
		_a					:				Optional[Any]				=							model(lowerCAmelCase_  )

		if base_model:
				_a					:				Dict				=							original_model(lowerCAmelCase_  )
				assert torch.allclose(lowerCAmelCase_						,      outputs.last_hidden_state[:, 0, :]						,      atol=1E-1  )
		else:
				_a					:				Optional[Any]				=							original_model(lowerCAmelCase_  )
				assert logits.shape == outputs.logits.shape
				assert torch.allclose(lowerCAmelCase_						,      outputs.logits						,      atol=1E-3  )

		Path(lowerCAmelCase_  ).mkdir(exist_ok=lowerCAmelCase_  )
		print(f"""Saving model {model_name} to {pytorch_dump_folder_path}"""  )
		model.save_pretrained(lowerCAmelCase_  )
		print(f"""Saving image processor to {pytorch_dump_folder_path}"""  )
		image_processor.save_pretrained(lowerCAmelCase_  )


if __name__ == "__main__":
							__lowerCAmelCase						      =       argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '''--model_name''',
							    default='''dino_vitb16''',
							    type=str,
							    help='''Name of the model trained with DINO you\'d like to convert.''',
							)
							parser.add_argument(
							    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
							)
							parser.add_argument(
							    '''--base_model''',
							    action='''store_true''',
							    help='''Whether to only convert the base model (no projection head weights).''',
							)

							parser.set_defaults(base_model=True)
							__lowerCAmelCase						      =       parser.parse_args()
							convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)









'''simple docstring'''

import os
import random
import sys

from . import cryptomath_module as cryptomath
from . import rabin_miller

__lowerCAmelCase						      =       3



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				int:
		print('Generating primitive root of p'  )
		while True:
				_a					:				List[Any]				=							random.randrange(3						,      lowerCAmelCase_  )
				if pow(lowerCAmelCase_						,      2						,      lowerCAmelCase_  ) == 1:
						continue
				if pow(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  ) == 1:
						continue
				return g



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				tuple[tuple[int, int, int, int], tuple[int, int]]:
		print('Generating prime p...'  )
		_a					:				int				=							rabin_miller.generate_large_prime(lowerCAmelCase_  )  # select large prime number.
		_a					:				List[str]				=							primitive_root(lowerCAmelCase_  )  # one primitive root on modulo p.
		_a					:				Any				=							random.randrange(3						,      lowerCAmelCase_  )  # private_key -> have to be greater than 2 for safety.
		_a					:				List[Any]				=							cryptomath.find_mod_inverse(pow(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )						,      lowerCAmelCase_  )

		_a					:				Tuple				=							(key_size, e_a, e_a, p)
		_a					:				str				=							(key_size, d)

		return public_key, private_key



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_  )      ->				None:
		if os.path.exists(f"""{name}_pubkey.txt"""  ) or os.path.exists(f"""{name}_privkey.txt"""  ):
				print('\nWARNING:'  )
				print(
				    f"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
				    'Use a different name or delete these files and re-run this program.'  )
				sys.exit()

		_a	, _a					:				Dict				=							generate_key(lowerCAmelCase_  )
		print(f"""\nWriting public key to file {name}_pubkey.txt..."""  )
		with open(f"""{name}_pubkey.txt"""						,      'w'  ) as fo:
				fo.write(f"""{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}"""  )

		print(f"""Writing private key to file {name}_privkey.txt..."""  )
		with open(f"""{name}_privkey.txt"""						,      'w'  ) as fo:
				fo.write(f"""{private_key[0]},{private_key[1]}"""  )



def 					__lowerCamelCase					(				)      ->				None:
		print('Making key files...'  )
		make_key_files('elgamal'						,      2048  )
		print('Key files generation successful'  )


if __name__ == "__main__":
							main()




