
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
			from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
			from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
			from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


lowerCamelCase__	=							DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

lowerCamelCase__	=							"main"
# Default branch name
lowerCamelCase__	=							"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
lowerCamelCase__	=							"aaaaaaa"
# This commit does not exist, so we should 404.

lowerCamelCase__	=							"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
lowerCamelCase__	=							"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def 							__A()		->				List[Any]:

		"""simple docstring"""






		print("""Welcome!""" )
		yield
		print("""Bye!""" )


@contextlib.contextmanager
def 							__A()		->				Optional[Any]:

		"""simple docstring"""






		print("""Bonjour!""" )
		yield
		print("""Au revoir!""" )







class        lowerCAmelCase__      (   unittest.TestCase	):

						def  A_				(			self				)					->      int:


								'''simple docstring'''

								assert transformers.__spec__ is not None
								assert importlib.util.find_spec("""transformers"""				) is not None







class        lowerCAmelCase__      (   unittest.TestCase	):

						@unittest.mock.patch("""sys.stdout"""       ,							new_callable=io.StringIO				)
						def  A_				(			self       ,							a				)					->      int:


								'''simple docstring'''

								with ContextManagers([]				):
										print("""Transformers are awesome!"""				)
								# The print statement adds a new line at the end of the output
								self.assertEqual(mock_stdout.getvalue()       ,							"""Transformers are awesome!\n"""				)

						@unittest.mock.patch("""sys.stdout"""       ,							new_callable=io.StringIO				)
						def  A_				(			self       ,							a				)					->      List[str]:


								'''simple docstring'''

								with ContextManagers([context_en()]				):
										print("""Transformers are awesome!"""				)
								# The output should be wrapped with an English welcome and goodbye
								self.assertEqual(mock_stdout.getvalue()       ,							"""Welcome!\nTransformers are awesome!\nBye!\n"""				)

						@unittest.mock.patch("""sys.stdout"""       ,							new_callable=io.StringIO				)
						def  A_				(			self       ,							a				)					->      Tuple:


								'''simple docstring'''

								with ContextManagers([context_fr(), context_en()]				):
										print("""Transformers are awesome!"""				)
								# The output should be wrapped with an English and French welcome and goodbye
								self.assertEqual(mock_stdout.getvalue()       ,							"""Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"""				)

						@require_torch
						def  A_				(			self				)					->      Union[str, Any]:


								'''simple docstring'''

								self.assertEqual(find_labels(__a				)       ,							["""labels"""]				)
								self.assertEqual(find_labels(__a				)       ,							["""labels""", """next_sentence_label"""]				)
								self.assertEqual(find_labels(__a				)       ,							["""start_positions""", """end_positions"""]				)







								class        lowerCAmelCase__      (   UpperCamelCase_	):
														pass




								self.assertEqual(find_labels(__a				)       ,							["""labels"""]				)

						@require_tf
						def  A_				(			self				)					->      List[Any]:


								'''simple docstring'''

								self.assertEqual(find_labels(__a				)       ,							["""labels"""]				)
								self.assertEqual(find_labels(__a				)       ,							["""labels""", """next_sentence_label"""]				)
								self.assertEqual(find_labels(__a				)       ,							["""start_positions""", """end_positions"""]				)







								class        lowerCAmelCase__      (   UpperCamelCase_	):
														pass




								self.assertEqual(find_labels(__a				)       ,							["""labels"""]				)







						@require_flax
						def  A_				(			self				)					->      int:


								'''simple docstring'''

								self.assertEqual(find_labels(__a				)       ,							[]				)
								self.assertEqual(find_labels(__a				)       ,							[]				)
								self.assertEqual(find_labels(__a				)       ,							[]				)







								class        lowerCAmelCase__      (   UpperCamelCase_	):
														pass




								self.assertEqual(find_labels(__a				)       ,							[]				)





import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List

import timm
import torch
import torch.nn as nn
from huggingface_hub import hf_hub_download
from torch import Tensor

from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification
from transformers.utils import logging


logging.set_verbosity_info()
lowerCamelCase__	=							logging.get_logger()







@dataclass
class        lowerCAmelCase__      :
						UpperCamelCase_							: nn.Module
						UpperCamelCase_							: List[nn.Module]	=		field(default_factory=__lowercase	)
						UpperCamelCase_							: list	=		field(default_factory=__lowercase	)

						def  A_				(			self       ,							a       ,							a       ,							a				)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	len(list(m.modules()				)				) == 1 or isinstance(a       ,							nn.Convad				) or isinstance(a       ,							nn.BatchNormad				)
								if has_not_submodules:
										self.traced.append(a				)

						def __call__(			self       ,							a				)					->      Optional[int]:


								'''simple docstring'''

								for m in self.module.modules():
										self.handles.append(m.register_forward_hook(self._forward_hook				)				)
								self.module(a				)
								[x.remove() for x in self.handles]
								return self







						@property
						def  A_				(			self				)					->      Optional[int]:


								'''simple docstring'''

								return list(filter(lambda a				: len(list(x.state_dict().keys()				)				) > 0       ,							self.traced				)				)







@dataclass
class        lowerCAmelCase__      :
						UpperCamelCase_							: nn.Module
						UpperCamelCase_							: nn.Module
						UpperCamelCase_							: int	=		0
						UpperCamelCase_							: List	=		field(default_factory=__lowercase	)
						UpperCamelCase_							: List	=		field(default_factory=__lowercase	)

						def __call__(			self       ,							a				)					->      List[Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	Tracker(self.dest				)(a				).parametrized
								_UpperCamelCase						    =	Tracker(self.src				)(a				).parametrized

								_UpperCamelCase						    =	list(filter(lambda a				: type(a				) not in self.src_skip       ,							a				)				)
								_UpperCamelCase						    =	list(filter(lambda a				: type(a				) not in self.dest_skip       ,							a				)				)

								if len(a				) != len(a				):
										raise Exception(
										    F'Numbers of operations are different. Source module has {len(a				)} operations while'
										    F' destination module has {len(a				)}.'				)

								for dest_m, src_m in zip(a       ,							a				):
										dest_m.load_state_dict(src_m.state_dict()				)
										if self.verbose == 1:
												print(F'Transfered from={src_m} to={dest_m}'				)




def 							__A(lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase = True )		->				Optional[Any]:

		"""simple docstring"""






		print(F'Converting {name}...' )
		with torch.no_grad():
				_UpperCamelCase						    =	timm.create_model(lowerCAmelCase						,  pretrained=lowerCAmelCase ).eval()
				_UpperCamelCase						    =	ResNetForImageClassification(lowerCAmelCase ).eval()
				_UpperCamelCase						    =	ModuleTransfer(src=lowerCAmelCase						,  dest=lowerCAmelCase )
				_UpperCamelCase						    =	torch.randn((1, 3, 2_2_4, 2_2_4) )
				module_transfer(lowerCAmelCase )

		assert torch.allclose(from_model(lowerCAmelCase )						,  our_model(lowerCAmelCase ).logits ), "The model logits don't match the original one."

		_UpperCamelCase						    =	F'resnet{"-".join(name.split("resnet" ) )}'
		print(lowerCAmelCase )

		if push_to_hub:
				our_model.push_to_hub(
				    repo_path_or_name=save_directory / checkpoint_name						,  commit_message="""Add model"""						,  use_temp_dir=lowerCAmelCase						,  )

				# we can use the convnext one
				_UpperCamelCase						    =	AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" )
				image_processor.push_to_hub(
				    repo_path_or_name=save_directory / checkpoint_name						,  commit_message="""Add image processor"""						,  use_temp_dir=lowerCAmelCase						,  )

				print(F'Pushed {checkpoint_name}' )


def 							__A(lowerCAmelCase						,  lowerCAmelCase = None						,  lowerCAmelCase = True )		->				Tuple:

		"""simple docstring"""






		_UpperCamelCase						    =	"""imagenet-1k-id2label.json"""
		_UpperCamelCase						    =	1_0_0_0
		_UpperCamelCase						    =	(1, num_labels)

		_UpperCamelCase						    =	"""huggingface/label-files"""
		_UpperCamelCase						    =	num_labels
		_UpperCamelCase						    =	json.load(open(hf_hub_download(lowerCAmelCase						,  lowerCAmelCase						,  repo_type="""dataset""" )						,  """r""" ) )
		_UpperCamelCase						    =	{int(lowerCAmelCase ): v for k, v in idalabel.items()}

		_UpperCamelCase						    =	idalabel
		_UpperCamelCase						    =	{v: k for k, v in idalabel.items()}

		_UpperCamelCase						    =	partial(lowerCAmelCase						,  num_labels=lowerCAmelCase						,  idalabel=lowerCAmelCase						,  labelaid=lowerCAmelCase )

		_UpperCamelCase						    =	{
		    """resnet18""": ImageNetPreTrainedConfig(
		        depths=[2, 2, 2, 2]						,  hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2]						,  layer_type="""basic""" ),
		    """resnet26""": ImageNetPreTrainedConfig(
		        depths=[2, 2, 2, 2]						,  hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,  layer_type="""bottleneck""" ),
		    """resnet34""": ImageNetPreTrainedConfig(
		        depths=[3, 4, 6, 3]						,  hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2]						,  layer_type="""basic""" ),
		    """resnet50""": ImageNetPreTrainedConfig(
		        depths=[3, 4, 6, 3]						,  hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,  layer_type="""bottleneck""" ),
		    """resnet101""": ImageNetPreTrainedConfig(
		        depths=[3, 4, 2_3, 3]						,  hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,  layer_type="""bottleneck""" ),
		    """resnet152""": ImageNetPreTrainedConfig(
		        depths=[3, 8, 3_6, 3]						,  hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,  layer_type="""bottleneck""" ),
		}

		if model_name:
				convert_weight_and_push(lowerCAmelCase						,  names_to_config[model_name]						,  lowerCAmelCase						,  lowerCAmelCase )
		else:
				for model_name, config in names_to_config.items():
						convert_weight_and_push(lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase )
		return config, expected_shape


if __name__ == "__main__":
		lowerCamelCase__	=							argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    "--model_name",
		    default=None,
		    type=str,
		    help=(
		        "The name of the model you wish to convert, it must be one of the supported resnet* architecture,"
		        " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted."
		    ),
		)
		parser.add_argument(
		    "--pytorch_dump_folder_path",
		    default=None,
		    type=Path,
		    required=True,
		    help="Path to the output PyTorch model directory.",
		)
		parser.add_argument(
		    "--push_to_hub",
		    default=True,
		    type=bool,
		    required=False,
		    help="If True, push model and image processor to the hub.",
		)

		lowerCamelCase__	=							parser.parse_args()
		lowerCamelCase__	=							args.pytorch_dump_folder_path
		pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
		convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)



