


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 ConvNextConfig, ConvNextForImageClassification, ConvNextImageProcessor
from transformers.utils import logging


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







def     __magic_name__  (      lowerCAmelCase_):
	'''simple docstring'''


	lowerCamelCase_			:							Optional[int]      =       ConvNextConfig()

	if "tiny" in checkpoint_url:
		lowerCamelCase_			:							Any      =       [3, 3, 9, 3]
		lowerCamelCase_			:							str      =       [96, 192, 384, 768]
	if "small" in checkpoint_url:
		lowerCamelCase_			:							Dict      =       [3, 3, 27, 3]
		lowerCamelCase_			:							List[str]      =       [96, 192, 384, 768]
	if "base" in checkpoint_url:
		lowerCamelCase_			:							str      =       [3, 3, 27, 3]
		lowerCamelCase_			:							Optional[Any]      =       [128, 256, 512, 1024]
	if "large" in checkpoint_url:
		lowerCamelCase_			:							Any      =       [3, 3, 27, 3]
		lowerCamelCase_			:							List[Any]      =       [192, 384, 768, 1536]
	if "xlarge" in checkpoint_url:
		lowerCamelCase_			:							int      =       [3, 3, 27, 3]
		lowerCamelCase_			:							Dict      =       [256, 512, 1024, 2048]

	if "1k" in checkpoint_url:
		lowerCamelCase_			:							Tuple      =       1000
		lowerCamelCase_			:							str      =       "imagenet-1k-id2label.json"
		lowerCamelCase_			:							Union[str, Any]      =       (1, 1000)
	else:
		lowerCamelCase_			:							Union[str, Any]      =       2_1841
		lowerCamelCase_			:							Optional[Any]      =       "imagenet-22k-id2label.json"
		lowerCamelCase_			:							List[Any]      =       (1, 2_1841)

	lowerCamelCase_			:							List[Any]      =       "huggingface/label-files"
	lowerCamelCase_			:							Union[str, Any]      =       num_labels
	lowerCamelCase_			:							Optional[int]      =       json.load(open(hf_hub_download(lowerCAmelCase_      ,					lowerCAmelCase_      ,					repo_type="dataset")      ,					"r"))
	lowerCamelCase_			:							Dict      =       {int(lowerCAmelCase_): v for k, v in idalabel.items()}
	if "1k" not in checkpoint_url:
		# this dataset contains 21843 labels but the model only has 21841
		# we delete the classes as mentioned in https://github.com/google-research/big_transfer/issues/18
		del idalabel[9205]
		del idalabel[1_5027]
	lowerCamelCase_			:							int      =       idalabel
	lowerCamelCase_			:							List[Any]      =       {v: k for k, v in idalabel.items()}
	lowerCamelCase_			:							Dict      =       hidden_sizes
	lowerCamelCase_			:							Any      =       depths

	return config, expected_shape







def     __magic_name__  (      lowerCAmelCase_):
	'''simple docstring'''


	if "downsample_layers.0.0" in name:
		lowerCamelCase_			:							Union[str, Any]      =       name.replace("downsample_layers.0.0"      ,					"embeddings.patch_embeddings")
	if "downsample_layers.0.1" in name:
		lowerCamelCase_			:							List[Any]      =       name.replace("downsample_layers.0.1"      ,					"embeddings.norm")  # we rename to layernorm later on
	if "downsample_layers.1.0" in name:
		lowerCamelCase_			:							Tuple      =       name.replace("downsample_layers.1.0"      ,					"stages.1.downsampling_layer.0")
	if "downsample_layers.1.1" in name:
		lowerCamelCase_			:							Optional[Any]      =       name.replace("downsample_layers.1.1"      ,					"stages.1.downsampling_layer.1")
	if "downsample_layers.2.0" in name:
		lowerCamelCase_			:							Optional[Any]      =       name.replace("downsample_layers.2.0"      ,					"stages.2.downsampling_layer.0")
	if "downsample_layers.2.1" in name:
		lowerCamelCase_			:							int      =       name.replace("downsample_layers.2.1"      ,					"stages.2.downsampling_layer.1")
	if "downsample_layers.3.0" in name:
		lowerCamelCase_			:							List[Any]      =       name.replace("downsample_layers.3.0"      ,					"stages.3.downsampling_layer.0")
	if "downsample_layers.3.1" in name:
		lowerCamelCase_			:							Tuple      =       name.replace("downsample_layers.3.1"      ,					"stages.3.downsampling_layer.1")
	if "stages" in name and "downsampling_layer" not in name:
		# stages.0.0. for instance should be renamed to stages.0.layers.0.
		lowerCamelCase_			:							Dict      =       name[: len("stages.0")] + ".layers" + name[len("stages.0") :]
	if "stages" in name:
		lowerCamelCase_			:							Tuple      =       name.replace("stages"      ,					"encoder.stages")
	if "norm" in name:
		lowerCamelCase_			:							Tuple      =       name.replace("norm"      ,					"layernorm")
	if "gamma" in name:
		lowerCamelCase_			:							Any      =       name.replace("gamma"      ,					"layer_scale_parameter")
	if "head" in name:
		lowerCamelCase_			:							Optional[Any]      =       name.replace("head"      ,					"classifier")

	return name







def     __magic_name__  (      ):
	'''simple docstring'''


	lowerCamelCase_			:							Optional[int]      =       "http://images.cocodataset.org/val2017/000000039769.jpg"
	lowerCamelCase_			:							List[Any]      =       Image.open(requests.get(lowerCAmelCase_      ,					stream=lowerCAmelCase_).raw)
	return im







@torch.no_grad()
def     __magic_name__  (      lowerCAmelCase_      ,					lowerCAmelCase_):
	'''simple docstring'''


	lowerCamelCase_   ,lowerCamelCase_			:							Any      =       get_convnext_config(lowerCAmelCase_)
	# load original state_dict from URL
	lowerCamelCase_			:							List[str]      =       torch.hub.load_state_dict_from_url(lowerCAmelCase_)["model"]
	# rename keys
	for key in state_dict.copy().keys():
		lowerCamelCase_			:							List[Any]      =       state_dict.pop(lowerCAmelCase_)
		lowerCamelCase_			:							Dict      =       val
	# add prefix to all keys expect classifier head
	for key in state_dict.copy().keys():
		lowerCamelCase_			:							Any      =       state_dict.pop(lowerCAmelCase_)
		if not key.startswith("classifier"):
			lowerCamelCase_			:							Optional[Any]      =       "convnext." + key
		lowerCamelCase_			:							List[str]      =       val

	# load HuggingFace model
	lowerCamelCase_			:							int      =       ConvNextForImageClassification(lowerCAmelCase_)
	model.load_state_dict(lowerCAmelCase_)
	model.eval()

	# Check outputs on an image, prepared by ConvNextImageProcessor
	lowerCamelCase_			:							List[Any]      =       224 if "224" in checkpoint_url else 384
	lowerCamelCase_			:							Tuple      =       ConvNextImageProcessor(size=lowerCAmelCase_)
	lowerCamelCase_			:							int      =       image_processor(images=prepare_img()      ,					return_tensors="pt").pixel_values

	lowerCamelCase_			:							int      =       model(lowerCAmelCase_).logits

	# note: the logits below were obtained without center cropping
	if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth":
		lowerCamelCase_			:							List[Any]      =       torch.tensor([-0.12_10, -0.66_05, 0.19_18])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth":
		lowerCamelCase_			:							Any      =       torch.tensor([-0.44_73, -0.18_47, -0.63_65])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth":
		lowerCamelCase_			:							Tuple      =       torch.tensor([0.45_25, 0.75_39, 0.03_08])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
		lowerCamelCase_			:							Optional[Any]      =       torch.tensor([0.35_61, 0.63_50, -0.03_84])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth":
		lowerCamelCase_			:							Dict      =       torch.tensor([0.41_74, -0.09_89, 0.14_89])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
		lowerCamelCase_			:							Union[str, Any]      =       torch.tensor([0.25_13, -0.13_49, -0.16_13])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
		lowerCamelCase_			:							int      =       torch.tensor([1.29_80, 0.36_31, -0.11_98])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
		lowerCamelCase_			:							Optional[Any]      =       torch.tensor([1.29_63, 0.12_27, 0.17_23])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
		lowerCamelCase_			:							List[Any]      =       torch.tensor([1.79_56, 0.83_90, 0.28_20])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_224.pth":
		lowerCamelCase_			:							Dict      =       torch.tensor([-0.28_22, -0.05_02, -0.08_78])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_384.pth":
		lowerCamelCase_			:							Tuple      =       torch.tensor([-0.56_72, -0.07_30, -0.43_48])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_224.pth":
		lowerCamelCase_			:							Union[str, Any]      =       torch.tensor([0.26_81, 0.23_65, 0.62_46])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_384.pth":
		lowerCamelCase_			:							Union[str, Any]      =       torch.tensor([-0.26_42, 0.39_31, 0.51_16])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_224_ema.pth":
		lowerCamelCase_			:							Optional[Any]      =       torch.tensor([-0.66_77, -0.18_73, -0.83_79])
	elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_384_ema.pth":
		lowerCamelCase_			:							Optional[int]      =       torch.tensor([-0.77_49, -0.29_67, -0.64_44])
	else:
		raise ValueError(F"""Unknown URL: {checkpoint_url}""")

	assert torch.allclose(logits[0, :3]      ,					lowerCAmelCase_      ,					atol=1E-3)
	assert logits.shape == expected_shape

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

	print("Pushing model to the hub...")
	lowerCamelCase_			:							Optional[int]      =       "convnext"
	if "tiny" in checkpoint_url:
		model_name += "-tiny"
	elif "small" in checkpoint_url:
		model_name += "-small"
	elif "base" in checkpoint_url:
		model_name += "-base"
	elif "xlarge" in checkpoint_url:
		model_name += "-xlarge"
	elif "large" in checkpoint_url:
		model_name += "-large"
	if "224" in checkpoint_url:
		model_name += "-224"
	elif "384" in checkpoint_url:
		model_name += "-384"
	if "22k" in checkpoint_url and "1k" not in checkpoint_url:
		model_name += "-22k"
	if "22k" in checkpoint_url and "1k" in checkpoint_url:
		model_name += "-22k-1k"

	model.push_to_hub(
	    repo_path_or_name=Path(lowerCAmelCase_      ,					lowerCAmelCase_)      ,					organization="nielsr"      ,					commit_message="Add model"      ,					)


if __name__ == "__main__":
							__magic_name__       					=      argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '''--checkpoint_url''',
							    default='''https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth''',
							    type=str,
							    help='''URL of the original ConvNeXT checkpoint you\'d like to convert.''',
							)
							parser.add_argument(
							    '''--pytorch_dump_folder_path''',
							    default=None,
							    type=str,
							    required=True,
							    help='''Path to the output PyTorch model directory.''',
							)

							__magic_name__       					=      parser.parse_args()
							convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)





__magic_name__       					=      {
    '''0''': 1,
    '''1''': 1,
    '''2''': 2,
    '''3''': 6,
    '''4''': 2_4,
    '''5''': 1_2_0,
    '''6''': 7_2_0,
    '''7''': 5_0_4_0,
    '''8''': 4_0_3_2_0,
    '''9''': 3_6_2_8_8_0,
}

__magic_name__       					=      {1_4_5: 1_4_5}

__magic_name__       					=      {
    1_4_5: 0,
    1_6_9: 3,
    3_6_3_0_1: 3,
    1_4_5_4: 3,
    8_7_1: 2,
    4_5_3_6_1: 2,
    8_7_2: 2,
}







def     __magic_name__  (      lowerCAmelCase_):
	'''simple docstring'''


	if n in CACHE_SUM_DIGIT_FACTORIALS:
		return CACHE_SUM_DIGIT_FACTORIALS[n]
	lowerCamelCase_			:							List[str]      =       sum(DIGIT_FACTORIALS[let] for let in str(lowerCAmelCase_))
	lowerCamelCase_			:							List[str]      =       ret
	return ret







def     __magic_name__  (      lowerCAmelCase_      ,					lowerCAmelCase_ = None):
	'''simple docstring'''


	lowerCamelCase_			:							List[str]      =       previous or set()
	if n in CHAIN_LENGTH_CACHE:
		return CHAIN_LENGTH_CACHE[n]
	lowerCamelCase_			:							str      =       sum_digit_factorials(lowerCAmelCase_)
	if next_number in previous:
		lowerCamelCase_			:							List[str]      =       0
		return 0
	else:
		previous.add(lowerCAmelCase_)
		lowerCamelCase_			:							List[Any]      =       1 + chain_length(lowerCAmelCase_      ,					lowerCAmelCase_)
		lowerCamelCase_			:							Optional[int]      =       ret
		return ret







def     __magic_name__  (      lowerCAmelCase_ = 60      ,					lowerCAmelCase_ = 100_0000):
	'''simple docstring'''


	return sum(1 for i in range(1      ,					lowerCAmelCase_) if chain_length(lowerCAmelCase_) == num_terms)


if __name__ == "__main__":
							print(f'''{solution() = }''')

