


import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional

import yaml

from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool


# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
_lowerCAmelCase:						Any   				=       sys.version_info >= (3, 10)






def   _lowercase(					__a				:						int=None    ,     __a				:						Any=None     ):
							return field(default_factory=lambda: default    ,     metadata=__a     )




@dataclass
class       lowercase_					:
				snake_case	    =42
				snake_case	    =42
				snake_case	    =42
				snake_case	    =42







@dataclass
class       lowercase_					:
				snake_case	    =42
				snake_case	    =field(default='toto'      ,					metadata={'help': 'help message'}   )







@dataclass
class       lowercase_					:
				snake_case	    =False
				snake_case	    =True
				snake_case	    =None







class       lowercase_					(lowercase__   ):
				snake_case	    ='titi'
				snake_case	    ='toto'







class       lowercase_					(lowercase__   ):
				snake_case	    ='titi'
				snake_case	    ='toto'
				snake_case	    =42







@dataclass
class       lowercase_					:
				snake_case	    ="toto"





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =BasicEnum(self.foo)







@dataclass
class       lowercase_					:
				snake_case	    ="toto"





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =MixedTypeEnum(self.foo)







@dataclass
class       lowercase_					:
				snake_case	    =None
				snake_case	    =field(default=lowercase__      ,					metadata={'help': 'help message'}   )
				snake_case	    =None
				snake_case	    =list_field(default=[]   )
				snake_case	    =list_field(default=[]   )







@dataclass
class       lowercase_					:
				snake_case	    =list_field(default=[]   )
				snake_case	    =list_field(default=[1, 2, 3]   )
				snake_case	    =list_field(default=['Hallo', 'Bonjour', 'Hello']   )
				snake_case	    =list_field(default=[0.1, 0.2, 0.3]   )







@dataclass
class       lowercase_					:
				snake_case	    =field()
				snake_case	    =field()
				snake_case	    =field()





				def 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =BasicEnum(self.required_enum)







@dataclass
class       lowercase_					:
				snake_case	    =42
				snake_case	    =field()
				snake_case	    =None
				snake_case	    =field(default='toto'      ,					metadata={'help': 'help message'}   )
				snake_case	    =list_field(default=['Hallo', 'Bonjour', 'Hello']   )


if is_python_no_less_than_3_10:




	@dataclass
	class       lowercase_					:
					snake_case	    =False
					snake_case	    =True
					snake_case	    =None







	@dataclass
	class       lowercase_					:
					snake_case	    =None
					snake_case	    =field(default=lowercase__      ,					metadata={'help': 'help message'}   )
					snake_case	    =None
					snake_case	    =list_field(default=[]   )
					snake_case	    =list_field(default=[]   )







class       lowercase_					(unittest.TestCase   ):





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_)  -> int:
											self.assertEqual(len(a._actions)       ,  len(b._actions))
											for x, y in zip(a._actions       ,  b._actions):
																		a__      ={k: v for k, v in vars(lowercase_).items() if k != 'container'}
																		a__      ={k: v for k, v in vars(lowercase_).items() if k != 'container'}

																		# Choices with mixed type have custom function as "type"
																		# So we need to compare results directly for equality
																		if xx.get('choices'       ,  lowercase_) and yy.get('choices'       ,  lowercase_):
																									for expected_choice in yy["choices"] + xx["choices"]:
																																self.assertEqual(xx['type'](lowercase_)       ,  yy['type'](lowercase_))
																									del xx["type"], yy["type"]

																		self.assertEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument('--bar'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument('--baz'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument('--flag'       ,  type=lowercase_       ,  default=lowercase_       ,  const=lowercase_       ,  nargs='?')
											self.argparsersEqual(lowercase_       ,  lowercase_)

											a__      =['--foo', '1', '--baz', 'quux', '--bar', '0.5']
											((a__)    ,     )      =parser.parse_args_into_dataclasses(lowercase_       ,  look_for_args_file=lowercase_)
											self.assertFalse(example.flag)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo'       ,  default=42       ,  type=lowercase_)
											expected.add_argument('--baz'       ,  default='toto'       ,  type=lowercase_       ,  help='help message')
											self.argparsersEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo'       ,  type=lowercase_       ,  default=lowercase_       ,  const=lowercase_       ,  nargs='?')
											expected.add_argument('--baz'       ,  type=lowercase_       ,  default=lowercase_       ,  const=lowercase_       ,  nargs='?')
											# A boolean no_* argument always has to come after its "default: True" regular counter-part
											# and its default must be set to False
											expected.add_argument('--no_baz'       ,  action='store_false'       ,  default=lowercase_       ,  dest='baz')
											expected.add_argument('--opt'       ,  type=lowercase_       ,  default=lowercase_)

											a__      =[WithDefaultBoolExample]
											if is_python_no_less_than_3_10:
																		dataclass_types.append(lowercase_)

											for dataclass_type in dataclass_types:
																		a__      =HfArgumentParser(lowercase_)
																		self.argparsersEqual(lowercase_       ,  lowercase_)

																		a__      =parser.parse_args([])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  baz=lowercase_       ,  opt=lowercase_))

																		a__      =parser.parse_args(['--foo', '--no_baz'])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  baz=lowercase_       ,  opt=lowercase_))

																		a__      =parser.parse_args(['--foo', '--baz'])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  baz=lowercase_       ,  opt=lowercase_))

																		a__      =parser.parse_args(['--foo', 'True', '--baz', 'True', '--opt', 'True'])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  baz=lowercase_       ,  opt=lowercase_))

																		a__      =parser.parse_args(['--foo', 'False', '--baz', 'False', '--opt', 'False'])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  baz=lowercase_       ,  opt=lowercase_))





				def 						__UpperCamelCase    (				self)  -> str:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument(
											    '--foo'       ,  default='toto'       ,  choices=['titi', 'toto', 42]       ,  type=make_choice_type_function(['titi', 'toto', 42])       ,  )
											self.argparsersEqual(lowercase_       ,  lowercase_)

											a__      =parser.parse_args([])
											self.assertEqual(args.foo       ,  'toto')
											a__      =parser.parse_args_into_dataclasses([])[0]
											self.assertEqual(enum_ex.foo       ,  MixedTypeEnum.toto)

											a__      =parser.parse_args(['--foo', 'titi'])
											self.assertEqual(args.foo       ,  'titi')
											a__      =parser.parse_args_into_dataclasses(['--foo', 'titi'])[0]
											self.assertEqual(enum_ex.foo       ,  MixedTypeEnum.titi)

											a__      =parser.parse_args(['--foo', '42'])
											self.assertEqual(args.foo       ,  42)
											a__      =parser.parse_args_into_dataclasses(['--foo', '42'])[0]
											self.assertEqual(enum_ex.foo       ,  MixedTypeEnum.fourtytwo)





				def 						__UpperCamelCase    (				self)  -> List[Any]:




											@dataclass
											class       lowercase_					:
															snake_case	    ="toto"







											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument(
											    '--foo'       ,  default='toto'       ,  choices=('titi', 'toto', 42)       ,  type=make_choice_type_function(['titi', 'toto', 42])       ,  )
											self.argparsersEqual(lowercase_       ,  lowercase_)

											a__      =parser.parse_args([])
											self.assertEqual(args.foo       ,  'toto')

											a__      =parser.parse_args(['--foo', 'titi'])
											self.assertEqual(args.foo       ,  'titi')

											a__      =parser.parse_args(['--foo', '42'])
											self.assertEqual(args.foo       ,  42)





				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo_int'       ,  nargs='+'       ,  default=[]       ,  type=lowercase_)
											expected.add_argument('--bar_int'       ,  nargs='+'       ,  default=[1, 2, 3]       ,  type=lowercase_)
											expected.add_argument('--foo_str'       ,  nargs='+'       ,  default=['Hallo', 'Bonjour', 'Hello']       ,  type=lowercase_)
											expected.add_argument('--foo_float'       ,  nargs='+'       ,  default=[0.1, 0.2, 0.3]       ,  type=lowercase_)

											self.argparsersEqual(lowercase_       ,  lowercase_)

											a__      =parser.parse_args([])
											self.assertEqual(
											    lowercase_       ,  Namespace(foo_int=[]       ,  bar_int=[1, 2, 3]       ,  foo_str=['Hallo', 'Bonjour', 'Hello']       ,  foo_float=[0.1, 0.2, 0.3])       ,  )

											a__      =parser.parse_args('--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'.split())
											self.assertEqual(lowercase_       ,  Namespace(foo_int=[1]       ,  bar_int=[2, 3]       ,  foo_str=['a', 'b', 'c']       ,  foo_float=[0.1, 0.7]))





				def 						__UpperCamelCase    (				self)  -> Dict:
											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo'       ,  default=lowercase_       ,  type=lowercase_)
											expected.add_argument('--bar'       ,  default=lowercase_       ,  type=lowercase_       ,  help='help message')
											expected.add_argument('--baz'       ,  default=lowercase_       ,  type=lowercase_)
											expected.add_argument('--ces'       ,  nargs='+'       ,  default=[]       ,  type=lowercase_)
											expected.add_argument('--des'       ,  nargs='+'       ,  default=[]       ,  type=lowercase_)

											a__      =[OptionalExample]
											if is_python_no_less_than_3_10:
																		dataclass_types.append(lowercase_)

											for dataclass_type in dataclass_types:
																		a__      =HfArgumentParser(lowercase_)

																		self.argparsersEqual(lowercase_       ,  lowercase_)

																		a__      =parser.parse_args([])
																		self.assertEqual(lowercase_       ,  Namespace(foo=lowercase_       ,  bar=lowercase_       ,  baz=lowercase_       ,  ces=[]       ,  des=[]))

																		a__      =parser.parse_args('--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'.split())
																		self.assertEqual(lowercase_       ,  Namespace(foo=12       ,  bar=3.14       ,  baz='42'       ,  ces=['a', 'b', 'c']       ,  des=[1, 2, 3]))





				def 						__UpperCamelCase    (				self)  -> str:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument('--required_list'       ,  nargs='+'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument('--required_str'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument(
											    '--required_enum'       ,  type=make_choice_type_function(['titi', 'toto'])       ,  choices=['titi', 'toto']       ,  required=lowercase_       ,  )
											self.argparsersEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> str:
											a__      =HfArgumentParser(lowercase_)

											a__      =argparse.ArgumentParser()
											expected.add_argument('--foo'       ,  type=lowercase_       ,  required=lowercase_)
											expected.add_argument(
											    '--required_enum'       ,  type=make_choice_type_function(['titi', 'toto'])       ,  choices=['titi', 'toto']       ,  required=lowercase_       ,  )
											expected.add_argument('--opt'       ,  type=lowercase_       ,  default=lowercase_)
											expected.add_argument('--baz'       ,  default='toto'       ,  type=lowercase_       ,  help='help message')
											expected.add_argument('--foo_str'       ,  nargs='+'       ,  default=['Hallo', 'Bonjour', 'Hello']       ,  type=lowercase_)
											self.argparsersEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =HfArgumentParser(lowercase_)

											a__      ={
											    'foo': 12,
											    'bar': 3.14,
											    'baz': '42',
											    'flag': True,
											}

											a__      =parser.parse_dict(lowercase_)[0]
											a__      =BasicExample(**lowercase_)
											self.assertEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =HfArgumentParser(lowercase_)

											a__      ={
											    'foo': 12,
											    'bar': 3.14,
											    'baz': '42',
											    'flag': True,
											    'extra': 42,
											}

											self.assertRaises(lowercase_       ,  parser.parse_dict       ,  lowercase_       ,  allow_extra_keys=lowercase_)





				def 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =HfArgumentParser(lowercase_)

											a__      ={
											    'foo': 12,
											    'bar': 3.14,
											    'baz': '42',
											    'flag': True,
											}
											with tempfile.TemporaryDirectory() as tmp_dir:
																		a__      =os.path.join(lowercase_       ,  'temp_json')
																		os.mkdir(lowercase_)
																		with open(temp_local_path + '.json'       ,  'w+') as f:
																									json.dump(lowercase_       ,  lowercase_)
																		a__      =parser.parse_yaml_file(Path(temp_local_path + '.json'))[0]

											a__      =BasicExample(**lowercase_)
											self.assertEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> Any:
											a__      =HfArgumentParser(lowercase_)

											a__      ={
											    'foo': 12,
											    'bar': 3.14,
											    'baz': '42',
											    'flag': True,
											}
											with tempfile.TemporaryDirectory() as tmp_dir:
																		a__      =os.path.join(lowercase_       ,  'temp_yaml')
																		os.mkdir(lowercase_)
																		with open(temp_local_path + '.yaml'       ,  'w+') as f:
																									yaml.dump(lowercase_       ,  lowercase_)
																		a__      =parser.parse_yaml_file(Path(temp_local_path + '.yaml'))[0]
											a__      =BasicExample(**lowercase_)
											self.assertEqual(lowercase_       ,  lowercase_)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =HfArgumentParser(lowercase_)
											self.assertIsNotNone(lowercase_)





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 (
    SwiftFormerConfig,
    SwiftFormerForImageClassification,
    ViTImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
_lowerCAmelCase:						List[str]   				=       logging.get_logger(__name__)

_lowerCAmelCase:						Tuple   				=       torch.device('cpu')






def   _lowercase(					):
							a__      ='http://images.cocodataset.org/val2017/000000039769.jpg'
							a__      =Image.open(requests.get(__a    ,     stream=__a     ).raw     )
							return im






def   _lowercase(					__a				:						Optional[Any]     ):
							if swiftformer_name == "swiftformer_xs":
														return torch.tensor([-2.1703e00, 2.1107e00, -2.0811e00, 8.8685e-01, 2.4360e-01]     )

							elif swiftformer_name == "swiftformer_s":
														return torch.tensor([3.9636e-01, 2.3478e-01, -1.6963e00, -1.7381e00, -8.6337e-01]     )

							elif swiftformer_name == "swiftformer_l1":
														return torch.tensor([-4.2768e-01, -4.7429e-01, -1.0897e00, -1.0248e00, 3.5523e-02]     )

							elif swiftformer_name == "swiftformer_l3":
														return torch.tensor([-2.5330e-01, 2.4211e-01, -6.0185e-01, -8.2789e-01, -6.0446e-02]     )






def   _lowercase(					__a				:						int    ,     __a				:						int    ,     __a				:						Optional[Any]     ):
							a__      =dct.pop(__a     )
							a__      =val






def   _lowercase(					__a				:						Optional[Any]     ):
							a__      =[]
							for k in state_dict.keys():
														a__      =k
														if ".pwconv" in k:
																					a__      =k_new.replace('.pwconv'    ,     '.point_wise_conv'     )
														if ".dwconv" in k:
																					a__      =k_new.replace('.dwconv'    ,     '.depth_wise_conv'     )
														if ".Proj." in k:
																					a__      =k_new.replace('.Proj.'    ,     '.proj.'     )
														if "patch_embed" in k_new:
																					a__      =k_new.replace('patch_embed'    ,     'swiftformer.patch_embed.patch_embedding'     )
														if "network" in k_new:
																					a__      =k_new.split('.'     )
																					if ls[2].isdigit():
																												a__      ='swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:]     )
																					else:
																												a__      =k_new.replace('network'    ,     'swiftformer.encoder.network'     )
														rename_keys.append((k, k_new)     )
							return rename_keys






@torch.no_grad()
def   _lowercase(					__a				:						Union[str, Any]    ,     __a				:						int    ,     __a				:						str     ):
							a__      =SwiftFormerConfig()

							# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
							a__      =1000
							a__      ='huggingface/label-files'
							a__      ='imagenet-1k-id2label.json'
							a__      =json.load(open(hf_hub_download(__a    ,     __a    ,     repo_type='dataset'     )    ,     'r'     )     )
							a__      ={int(__a     ): v for k, v in idalabel.items()}
							a__      =idalabel
							a__      ={v: k for k, v in idalabel.items()}

							# size of the architecture
							if swiftformer_name == "swiftformer_xs":
														a__      =[3, 3, 6, 4]
														a__      =[48, 56, 112, 220]

							elif swiftformer_name == "swiftformer_s":
														a__      =[3, 3, 9, 6]
														a__      =[48, 64, 168, 224]

							elif swiftformer_name == "swiftformer_l1":
														a__      =[4, 3, 10, 5]
														a__      =[48, 96, 192, 384]

							elif swiftformer_name == "swiftformer_l3":
														a__      =[4, 4, 12, 6]
														a__      =[64, 128, 320, 512]

							# load state_dict of original model, remove and rename some keys
							if original_ckpt:
														if original_ckpt.startswith('https'     ):
																					a__      =torch.hub.load_state_dict_from_url(__a    ,     map_location='cpu'    ,     check_hash=__a     )
														else:
																					a__      =torch.load(__a    ,     map_location='cpu'     )
							a__      =checkpoint

							a__      =create_rename_keys(__a     )
							for rename_key_src, rename_key_dest in rename_keys:
														rename_key(__a    ,     __a    ,     __a     )

							# load HuggingFace model
							a__      =SwiftFormerForImageClassification(__a     ).eval()
							hf_model.load_state_dict(__a     )

							# prepare test inputs
							a__      =prepare_img()
							a__      =ViTImageProcessor.from_pretrained('preprocessor_config'     )
							a__      =processor(images=__a    ,     return_tensors='pt'     )

							# compare outputs from both models
							a__      =get_expected_output(__a     )
							a__      =hf_model(inputs['pixel_values']     ).logits

							assert hf_logits.shape == torch.Size([1, 1000]     )
							assert torch.allclose(hf_logits[0, 0:5]    ,     __a    ,     atol=1e-3     )

							Path(__a     ).mkdir(exist_ok=__a     )
							print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}"""     )
							hf_model.save_pretrained(__a     )


if __name__ == "__main__":
	_lowerCAmelCase:						Optional[Any]   				=       argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    '--swiftformer_name',
	    default='swiftformer_xs',
	    choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'],
	    type=str,
	    help='Name of the SwiftFormer model you\'d like to convert.',
	)
	parser.add_argument(
	    '--pytorch_dump_folder_path',
	    default='./converted_outputs/',
	    type=str,
	    help='Path to the output PyTorch model directory.',
	)
	parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.')

	_lowerCAmelCase:						Optional[int]   				=       parser.parse_args()
	convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)

