




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()
__A        =    logging.get_logger(__name__)







def 			lowerCamelCase_		(       UpperCamelCase__				:      List[str] ,     UpperCamelCase__				:      Union[str, Any]=False      )     ->       Union[str, Any]:





				"""simple docstring"""


				__lowerCamelCase		       =    []
				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"
								__lowerCamelCase		       =    [(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_		(       UpperCamelCase__				:      Optional[int] ,     UpperCamelCase__				:      List[Any] ,     UpperCamelCase__				:      Optional[int]=False      )     ->       str:





				"""simple docstring"""


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







def 			lowerCamelCase_		(       UpperCamelCase__				:      int      )     ->       List[Any]:





				"""simple docstring"""


				__lowerCamelCase		       =    ['head.weight', 'head.bias']
				for k in ignore_keys:
								state_dict.pop(UpperCamelCase__ ,     UpperCamelCase__      )







def 			lowerCamelCase_		(       UpperCamelCase__				:      Tuple ,     UpperCamelCase__				:      Tuple ,     UpperCamelCase__				:      Union[str, Any]      )     ->       Tuple:





				"""simple docstring"""


				__lowerCamelCase		       =    dct.pop(UpperCamelCase__      )
				__lowerCamelCase		       =    val







def 			lowerCamelCase_		(       )     ->       List[str]:





				"""simple docstring"""


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







@torch.no_grad()
def 			lowerCamelCase_		(       UpperCamelCase__				:      str ,     UpperCamelCase__				:      str ,     UpperCamelCase__				:      Dict=True      )     ->       Tuple:





				"""simple docstring"""


				__lowerCamelCase		       =    ViTConfig()
				# patch_size
				if model_name[-1] == "8":
								__lowerCamelCase		       =    8
				# set labels if required
				if not base_model:
								__lowerCamelCase		       =    1000
								__lowerCamelCase		       =    'huggingface/label-files'
								__lowerCamelCase		       =    'imagenet-1k-id2label.json'
								__lowerCamelCase		       =    json.load(open(hf_hub_download(UpperCamelCase__ ,     UpperCamelCase__ ,     repo_type='dataset'      ) ,     'r'      )      )
								__lowerCamelCase		       =    {int(UpperCamelCase__      ): v for k, v in idalabel.items()}
								__lowerCamelCase		       =    idalabel
								__lowerCamelCase		       =    {v: k for k, v in idalabel.items()}
				# size of the architecture
				if model_name in ["dino_vits8", "dino_vits16"]:
								__lowerCamelCase		       =    384
								__lowerCamelCase		       =    1536
								__lowerCamelCase		       =    12
								__lowerCamelCase		       =    6

				# load original model from torch hub
				__lowerCamelCase		       =    torch.hub.load('facebookresearch/dino:main' ,     UpperCamelCase__      )
				original_model.eval()

				# load state_dict of original model, remove and rename some keys
				__lowerCamelCase		       =    original_model.state_dict()
				if base_model:
								remove_classification_head_(UpperCamelCase__      )
				__lowerCamelCase		       =    create_rename_keys(UpperCamelCase__ ,     base_model=UpperCamelCase__      )
				for src, dest in rename_keys:
								rename_key(UpperCamelCase__ ,     UpperCamelCase__ ,     UpperCamelCase__      )
				read_in_q_k_v(UpperCamelCase__ ,     UpperCamelCase__ ,     UpperCamelCase__      )

				# load HuggingFace model
				if base_model:
								__lowerCamelCase		       =    ViTModel(UpperCamelCase__ ,     add_pooling_layer=UpperCamelCase__      ).eval()
				else:
								__lowerCamelCase		       =    ViTForImageClassification(UpperCamelCase__      ).eval()
				model.load_state_dict(UpperCamelCase__      )

				# Check outputs on an image, prepared by ViTImageProcessor
				__lowerCamelCase		       =    ViTImageProcessor()
				__lowerCamelCase		       =    image_processor(images=prepare_img() ,     return_tensors='pt'      )
				__lowerCamelCase		       =    encoding['pixel_values']
				__lowerCamelCase		       =    model(UpperCamelCase__      )

				if base_model:
								__lowerCamelCase		       =    original_model(UpperCamelCase__      )
								assert torch.allclose(UpperCamelCase__ ,     outputs.last_hidden_state[:, 0, :] ,     atol=1E-1      )
				else:
								__lowerCamelCase		       =    original_model(UpperCamelCase__      )
								assert logits.shape == outputs.logits.shape
								assert torch.allclose(UpperCamelCase__ ,     outputs.logits ,     atol=1E-3      )

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


if __name__ == "__main__":
					__A        =    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)
					__A        =    parser.parse_args()
					convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)






def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''')     )
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		lowercase__            =      credit_card_number
		lowercase__            =      0
		lowercase__            =      len(SCREAMING_SNAKE_CASE     ) - 2
		for i in range(SCREAMING_SNAKE_CASE						,				-1						,				-2     ):
				#  double the value of every second digit
				lowercase__            =      int(cc_number[i]     )
				digit *= 2
				# If doubling of a number results in a two digit number
				# i.e greater than 9(e.g., 6 × 2 = 12),
				# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
				# to get a single digit number.
				if digit > 9:
						digit %= 10
						digit += 1
				lowercase__            =      cc_number[:i] + str(SCREAMING_SNAKE_CASE     ) + cc_number[i + 1 :]
				total += digit

		# Sum up the remaining digits
		for i in range(len(SCREAMING_SNAKE_CASE     ) - 1						,				-1						,				-2     ):
				total += int(cc_number[i]     )

		return total % 10 == 0
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		lowercase__            =      f'{credit_card_number} is an invalid credit card number because'
		if not credit_card_number.isdigit():
				print(f'{error_message} it has nonnumerical characters.'     )
				return False

		if not 13 <= len(SCREAMING_SNAKE_CASE     ) <= 16:
				print(f'{error_message} of its length.'     )
				return False

		if not validate_initial_digits(SCREAMING_SNAKE_CASE     ):
				print(f'{error_message} of its first two digits.'     )
				return False

		if not luhn_validation(SCREAMING_SNAKE_CASE     ):
				print(f'{error_message} it fails the Luhn check.'     )
				return False

		print(f'{credit_card_number} is a valid credit card number.'     )
		return True


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			validate_credit_card_number('4111111111111111')
			validate_credit_card_number('32323')


