





import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
					import torch

					from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin


class     A     :
			'''simple docstring'''




			def __init__(     self  :       Optional[int]				,      __lowerCAmelCase  :       Tuple				,      __lowerCAmelCase  :       Optional[int]=None				,      __lowerCAmelCase  :       Dict=None				,      __lowerCAmelCase  :       Optional[int]=None				,      __lowerCAmelCase  :       Tuple="resnet50"				,      __lowerCAmelCase  :       List[Any]=3				,      __lowerCAmelCase  :       str=32				,      __lowerCAmelCase  :       Optional[int]=3				,      __lowerCAmelCase  :       Optional[int]=True				,      __lowerCAmelCase  :       Optional[int]=True				,      )      ->      List[str]:







					"""simple docstring"""






					A__     =  parent
					A__     =  out_indices if out_indices is not None else [4]
					A__     =  stage_names
					A__     =  out_features
					A__     =  backbone
					A__     =  batch_size
					A__     =  image_size
					A__     =  num_channels
					A__     =  use_pretrained_backbone
					A__     =  is_training






			def   a_			(     self  :       List[str]  )      ->      List[str]:







					"""simple docstring"""






					A__     =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )
					A__     =  self.get_config()

					return config, pixel_values






			def   a_			(     self  :       Union[str, Any]  )      ->      Union[str, Any]:







					"""simple docstring"""






					return TimmBackboneConfig(
					    image_size=self.image_size				,      num_channels=self.num_channels				,      out_features=self.out_features				,      out_indices=self.out_indices				,      stage_names=self.stage_names				,      use_pretrained_backbone=self.use_pretrained_backbone				,      backbone=self.backbone				,      )






			def   a_			(     self  :       Optional[int]				,      __lowerCAmelCase  :       Dict				,      __lowerCAmelCase  :       Optional[int]  )      ->      int:







					"""simple docstring"""






					A__     =  TimmBackbone(config=lowerCamelCase_  )
					model.to(lowerCamelCase_  )
					model.eval()
					with torch.no_grad():
							A__     =  model(lowerCamelCase_  )
					self.parent.assertEqual(
					    result.feature_map[-1].shape				,      (self.batch_size, model.channels[-1], 14, 14)				,      )







			def   a_			(     self  :       List[Any]  )      ->      str:







					"""simple docstring"""






					A__     =  self.prepare_config_and_inputs()
					A__     =  config_and_inputs
					A__     =  {'pixel_values': pixel_values}
					return config, inputs_dict


@require_torch
@require_timm
class     A     (_UpperCamelCase  ,	_UpperCamelCase  ,	_UpperCamelCase  ,	unittest.TestCase       ):
			'''simple docstring'''




			__lowerCamelCase      :			str							     =       (TimmBackbone,) if is_torch_available() else ()
			__lowerCamelCase      :			List[str]							     =       {'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
			__lowerCamelCase      :			Optional[Any]							     =       False
			__lowerCamelCase      :			int							     =       False
			__lowerCamelCase      :			Optional[Any]							     =       False
			__lowerCamelCase      :			Optional[Any]							     =       False






			def   a_			(     self  :       Optional[Any]  )      ->      int:







					"""simple docstring"""






					A__     =  TimmBackboneModelTester(self  )
					A__     =  ConfigTester(self				,      config_class=lowerCamelCase_				,      has_text_modality=lowerCamelCase_  )






			def   a_			(     self  :       List[str]  )      ->      Tuple:







					"""simple docstring"""






					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()






			def   a_			(     self  :       Tuple  )      ->      Dict:







					"""simple docstring"""






					A__     =  'resnet18'
					A__     =  'microsoft/resnet-18'

					A__     =  AutoBackbone.from_pretrained(lowerCamelCase_				,      use_timm_backbone=lowerCamelCase_  )
					A__     =  AutoBackbone.from_pretrained(lowerCamelCase_  )

					self.assertEqual(len(timm_model.out_features  )				,      len(transformers_model.out_features  )  )
					self.assertEqual(len(timm_model.stage_names  )				,      len(transformers_model.stage_names  )  )
					self.assertEqual(timm_model.channels				,      transformers_model.channels  )
					# Out indices are set to the last layer by default. For timm models, we don't know
					# the number of layers in advance, so we set it to (-1,), whereas for transformers
					# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
					self.assertEqual(timm_model.out_indices				,      (-1,)  )
					self.assertEqual(transformers_model.out_indices				,      [len(timm_model.stage_names  ) - 1]  )

					A__     =  AutoBackbone.from_pretrained(lowerCamelCase_				,      use_timm_backbone=lowerCamelCase_				,      out_indices=[1, 2, 3]  )
					A__     =  AutoBackbone.from_pretrained(lowerCamelCase_				,      out_indices=[1, 2, 3]  )

					self.assertEqual(timm_model.out_indices				,      transformers_model.out_indices  )
					self.assertEqual(len(timm_model.out_features  )				,      len(transformers_model.out_features  )  )
					self.assertEqual(timm_model.channels				,      transformers_model.channels  )






			@unittest.skip("""TimmBackbone doesn\'t support feed forward chunking"""  )
			def   a_			(     self  :       Union[str, Any]  )      ->      Optional[int]:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone doesn\'t have num_hidden_layers attribute"""  )
			def   a_			(     self  :       Optional[Any]  )      ->      Any:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone initialization is managed on the timm side"""  )
			def   a_			(     self  :       Union[str, Any]  )      ->      Any:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds"""  )
			def   a_			(     self  :       Any  )      ->      Any:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds"""  )
			def   a_			(     self  :       Optional[Any]  )      ->      str:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint"""  )
			def   a_			(     self  :       Union[str, Any]  )      ->      Tuple:







					"""simple docstring"""






					pass






			@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""  )
			def   a_			(     self  :       Dict  )      ->      Any:







					"""simple docstring"""






					pass






			@unittest.skip("""model weights aren\'t tied in TimmBackbone."""  )
			def   a_			(     self  :       List[Any]  )      ->      Union[str, Any]:







					"""simple docstring"""






					pass






			@unittest.skip("""model weights aren\'t tied in TimmBackbone."""  )
			def   a_			(     self  :       List[Any]  )      ->      Any:







					"""simple docstring"""






					pass






			@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""  )
			def   a_			(     self  :       Any  )      ->      int:







					"""simple docstring"""






					pass






			@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""  )
			def   a_			(     self  :       Optional[Any]  )      ->      Optional[int]:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone doesn\'t have hidden size info in its configuration."""  )
			def   a_			(     self  :       Optional[Any]  )      ->      Union[str, Any]:







					"""simple docstring"""






					pass






			@unittest.skip("""TimmBackbone doesn\'t support output_attentions."""  )
			def   a_			(     self  :       Any  )      ->      Optional[Any]:







					"""simple docstring"""






					pass






			@unittest.skip("""Safetensors is not supported by timm."""  )
			def   a_			(     self  :       Dict  )      ->      Optional[Any]:







					"""simple docstring"""






					pass






			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
			def   a_			(     self  :       List[str]  )      ->      int:







					"""simple docstring"""






					pass






			def   a_			(     self  :       List[str]  )      ->      Dict:







					"""simple docstring"""






					A__     =  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							A__     =  model_class(lowerCamelCase_  )
							A__     =  inspect.signature(model.forward  )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							A__     =  [*signature.parameters.keys()]

							A__     =  ['pixel_values']
							self.assertListEqual(arg_names[:1]				,      lowerCamelCase_  )






			def   a_			(     self  :       Optional[int]  )      ->      Union[str, Any]:







					"""simple docstring"""






					A__     =  self.model_tester.prepare_config_and_inputs_for_common()
					A__     =  True
					A__     =  self.has_attentions

					# no need to test all models as different heads yield the same functionality
					A__     =  self.all_model_classes[0]
					A__     =  model_class(lowerCamelCase_  )
					model.to(lowerCamelCase_  )

					A__     =  self._prepare_for_class(lowerCamelCase_				,      lowerCamelCase_  )
					A__     =  model(**lowerCamelCase_  )
					A__     =  outputs[0][-1]

					# Encoder-/Decoder-only models
					A__     =  outputs.hidden_states[0]
					hidden_states.retain_grad()

					if self.has_attentions:
							A__     =  outputs.attentions[0]
							attentions.retain_grad()

					output.flatten()[0].backward(retain_graph=lowerCamelCase_  )

					self.assertIsNotNone(hidden_states.grad  )

					if self.has_attentions:
							self.assertIsNotNone(attentions.grad  )







			def   a_			(     self  :       Optional[int]  )      ->      int:







					"""simple docstring"""






					A__     =  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							A__     =  model_class(lowerCamelCase_  )
							model.to(lowerCamelCase_  )
							model.eval()
							A__     =  model(**lowerCamelCase_  )

							self.assertEqual(len(result.feature_maps  )				,      len(config.out_indices  )  )
							self.assertEqual(len(model.channels  )				,      len(config.out_indices  )  )

							# Check output of last stage is taken if out_features=None, out_indices=None
							A__     =  copy.deepcopy(lowerCamelCase_  )
							A__     =  None
							A__     =  model_class(lowerCamelCase_  )
							model.to(lowerCamelCase_  )
							model.eval()
							A__     =  model(**lowerCamelCase_  )

							self.assertEqual(len(result.feature_maps  )				,      1  )
							self.assertEqual(len(model.channels  )				,      1  )

							# Check backbone can be initialized with fresh weights
							A__     =  copy.deepcopy(lowerCamelCase_  )
							A__     =  False
							A__     =  model_class(lowerCamelCase_  )
							model.to(lowerCamelCase_  )
							model.eval()
							A__     =  model(**lowerCamelCase_  )










import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey


class       __lowerCAmelCase					:


	'''simple docstring'''





	def __init__(						self:						List[str],					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						int,					lowerCamelCase_:						int			):
			if dst_width < 0 or dst_height < 0:
					raise ValueError('Destination width/height should be > 0'			)

			lowercase__					:      str      =		img
			lowercase__					:      Tuple      =		img.shape[1]
			lowercase__					:      str      =		img.shape[0]
			lowercase__					:      Tuple      =		dst_width
			lowercase__					:      Any      =		dst_height

			lowercase__					:      Tuple      =		self.src_w / self.dst_w
			lowercase__					:      Union[str, Any]      =		self.src_h / self.dst_h

			lowercase__					:      List[Any]      =		(
			    np.ones((self.dst_h, self.dst_w, 3),					np.uinta			) * 255
			)

	def    snake_case__(						self:						Dict			):
			for i in range(self.dst_h			):
					for j in range(self.dst_w			):
							lowercase__					:      Tuple      =		self.img[self.get_y(lowerCamelCase_			)][self.get_x(lowerCamelCase_			)]

	def    snake_case__(						self:						List[str],					lowerCamelCase_:						int			):
			return int(self.ratio_x * x			)





	def    snake_case__(						self:						int,					lowerCamelCase_:						int			):
			return int(self.ratio_y * y			)


if __name__ == "__main__":
			__UpperCamelCase,	__UpperCamelCase:	List[Any] = 8_0_0, 6_0_0
			__UpperCamelCase:	Optional[Any] = imread("""image_data/lena.jpg""", 1)
			__UpperCamelCase:	Union[str, Any] = NearestNeighbour(im, dst_w, dst_h)
			n.process()

			imshow(
			    F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output
			)
			waitKey(0)
			destroyAllWindows()


