



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import TFCvtForImageClassification, TFCvtModel
	from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor






class 						lowercase		(					snake_case__):






	"""simple docstring"""


	def     _SCREAMING_SNAKE_CASE						(      self      :		str	)     ->					List[Any]:
							UpperCAmelCase_=  self.config_class(**self.inputs_dict	)
							self.parent.assertTrue(hasattr(__UpperCAmelCase		,    """embed_dim"""	)	)
							self.parent.assertTrue(hasattr(__UpperCAmelCase		,    """num_heads"""	)	)






class 						lowercase		:






	"""simple docstring"""


	def __init__(      self      :		List[Any]		,    __UpperCAmelCase      :		Any		,    __UpperCAmelCase      :		Union[str, Any]=13		,    __UpperCAmelCase      :		Union[str, Any]=64		,    __UpperCAmelCase      :		List[Any]=3		,    __UpperCAmelCase      :		Optional[Any]=[16, 48, 96]		,    __UpperCAmelCase      :		List[Any]=[1, 3, 6]		,    __UpperCAmelCase      :		Dict=[1, 2, 10]		,    __UpperCAmelCase      :		Union[str, Any]=[7, 3, 3]		,    __UpperCAmelCase      :		Any=[4, 2, 2]		,    __UpperCAmelCase      :		int=[2, 1, 1]		,    __UpperCAmelCase      :		List[Any]=[2, 2, 2]		,    __UpperCAmelCase      :		Any=[False, False, True]		,    __UpperCAmelCase      :		Union[str, Any]=[0.0, 0.0, 0.0]		,    __UpperCAmelCase      :		int=0.02		,    __UpperCAmelCase      :		Any=1E-12		,    __UpperCAmelCase      :		List[Any]=True		,    __UpperCAmelCase      :		Optional[Any]=True		,    __UpperCAmelCase      :		Optional[int]=2		,    )     ->					Union[str, Any]:
							UpperCAmelCase_=  parent
							UpperCAmelCase_=  batch_size
							UpperCAmelCase_=  image_size
							UpperCAmelCase_=  patch_sizes
							UpperCAmelCase_=  patch_stride
							UpperCAmelCase_=  patch_padding
							UpperCAmelCase_=  is_training
							UpperCAmelCase_=  use_labels
							UpperCAmelCase_=  num_labels
							UpperCAmelCase_=  num_channels
							UpperCAmelCase_=  embed_dim
							UpperCAmelCase_=  num_heads
							UpperCAmelCase_=  stride_kv
							UpperCAmelCase_=  depth
							UpperCAmelCase_=  cls_token
							UpperCAmelCase_=  attention_drop_rate
							UpperCAmelCase_=  initializer_range
							UpperCAmelCase_=  layer_norm_eps




	def     _SCREAMING_SNAKE_CASE						(      self      :		Optional[int]	)     ->					List[Any]:
							UpperCAmelCase_=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

							UpperCAmelCase_=  None
							if self.use_labels:
													# create a random int32 tensor of given shape
													UpperCAmelCase_=  ids_tensor([self.batch_size]		,    self.num_labels	)

							UpperCAmelCase_=  self.get_config()
							return config, pixel_values, labels




	def     _SCREAMING_SNAKE_CASE						(      self      :		Any	)     ->					List[Any]:
							return CvtConfig(
							    image_size=self.image_size		,    num_labels=self.num_labels		,    num_channels=self.num_channels		,    embed_dim=self.embed_dim		,    num_heads=self.num_heads		,    patch_sizes=self.patch_sizes		,    patch_padding=self.patch_padding		,    patch_stride=self.patch_stride		,    stride_kv=self.stride_kv		,    depth=self.depth		,    cls_token=self.cls_token		,    attention_drop_rate=self.attention_drop_rate		,    initializer_range=self.initializer_range		,    )




	def     _SCREAMING_SNAKE_CASE						(      self      :		str		,    __UpperCAmelCase      :		List[Any]		,    __UpperCAmelCase      :		Optional[Any]		,    __UpperCAmelCase      :		List[str]	)     ->					Tuple:
							UpperCAmelCase_=  TFCvtModel(config=__UpperCAmelCase	)
							UpperCAmelCase_=  model(__UpperCAmelCase		,    training=__UpperCAmelCase	)
							UpperCAmelCase_=  (self.image_size, self.image_size)
							UpperCAmelCase_=  image_size[0], image_size[1]
							for i in range(len(self.depth	)	):
													UpperCAmelCase_=  floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
													UpperCAmelCase_=  floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
							self.parent.assertEqual(result.last_hidden_state.shape		,    (self.batch_size, self.embed_dim[-1], height, width)	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		List[str]		,    __UpperCAmelCase      :		List[Any]		,    __UpperCAmelCase      :		str		,    __UpperCAmelCase      :		str	)     ->					Optional[Any]:
							UpperCAmelCase_=  self.num_labels
							UpperCAmelCase_=  TFCvtForImageClassification(__UpperCAmelCase	)
							UpperCAmelCase_=  model(__UpperCAmelCase		,    labels=__UpperCAmelCase		,    training=__UpperCAmelCase	)
							self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.num_labels)	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		str	)     ->					List[str]:
							UpperCAmelCase_=  self.prepare_config_and_inputs()
							UpperCAmelCase_=  config_and_inputs
							UpperCAmelCase_=  {'pixel_values': pixel_values}
							return config, inputs_dict






@require_tf
class 						lowercase		(					snake_case__					,       snake_case__					,       unittest.TestCase):






	"""simple docstring"""


	a__ :   Dict						  =				(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	a__ :   Union[str, Any]						  =				(
	    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	a__ :   Any						  =				False
	a__ :   List[Any]						  =				False
	a__ :   Dict						  =				False
	a__ :   Any						  =				False
	a__ :   int						  =				False




	def     _SCREAMING_SNAKE_CASE						(      self      :		List[Any]	)     ->					int:
							UpperCAmelCase_=  TFCvtModelTester(self	)
							UpperCAmelCase_=  TFCvtConfigTester(self		,    config_class=__UpperCAmelCase		,    has_text_modality=__UpperCAmelCase		,    hidden_size=37	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		List[str]	)     ->					List[str]:
							self.config_tester.create_and_test_config_common_properties()
							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()




	@unittest.skip(reason="""Cvt does not output attentions"""	)
	def     _SCREAMING_SNAKE_CASE						(      self      :		List[Any]	)     ->					Dict:
							pass




	@unittest.skip(reason="""Cvt does not use inputs_embeds"""	)
	def     _SCREAMING_SNAKE_CASE						(      self      :		str	)     ->					List[Any]:
							pass




	@unittest.skip(reason="""Cvt does not support input and output embeddings"""	)
	def     _SCREAMING_SNAKE_CASE						(      self      :		Union[str, Any]	)     ->					List[str]:
							pass




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""	)	) == 0		,    reason="""TF does not support backprop for grouped convolutions on CPU."""		,    )
	def     _SCREAMING_SNAKE_CASE						(      self      :		Tuple	)     ->					Dict:
							super().test_dataset_conversion()




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""	)	) == 0		,    reason="""TF does not support backprop for grouped convolutions on CPU."""		,    )
	@slow
	def     _SCREAMING_SNAKE_CASE						(      self      :		Optional[Any]	)     ->					str:
							super().test_keras_fit()




	@unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""	)
	def     _SCREAMING_SNAKE_CASE						(      self      :		Any	)     ->					int:
							UpperCAmelCase_=  tf.keras.mixed_precision.Policy("""mixed_float16"""	)
							tf.keras.mixed_precision.set_global_policy(__UpperCAmelCase	)
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy("""float32"""	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		Union[str, Any]	)     ->					List[str]:
							UpperCAmelCase_=  self.model_tester.prepare_config_and_inputs_for_common()

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

													UpperCAmelCase_=  ['pixel_values']
													self.assertListEqual(arg_names[:1]		,    __UpperCAmelCase	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		Tuple	)     ->					List[Any]:
							def check_hidden_states_output(__UpperCAmelCase      :		Union[str, Any]		,    __UpperCAmelCase      :		Optional[Any]		,    __UpperCAmelCase      :		Tuple	):
													UpperCAmelCase_=  model_class(__UpperCAmelCase	)

													UpperCAmelCase_=  model(**self._prepare_for_class(__UpperCAmelCase		,    __UpperCAmelCase	)	)
													UpperCAmelCase_=  outputs.hidden_states

													UpperCAmelCase_=  len(self.model_tester.depth	)
													self.assertEqual(len(__UpperCAmelCase	)		,    __UpperCAmelCase	)

													# verify the first hidden states (first block)
													self.assertListEqual(
													    list(hidden_states[0].shape[-3:]	)		,    [
													        self.model_tester.embed_dim[0],
													        self.model_tester.image_size // 4,
													        self.model_tester.image_size // 4,
													    ]		,    )

							UpperCAmelCase_=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													UpperCAmelCase_=  True
													check_hidden_states_output(__UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase	)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													UpperCAmelCase_=  True

													check_hidden_states_output(__UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		Tuple	)     ->					Tuple:
							UpperCAmelCase_=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCAmelCase	)




	def     _SCREAMING_SNAKE_CASE						(      self      :		int	)     ->					Union[str, Any]:
							UpperCAmelCase_=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase	)




	@slow
	def     _SCREAMING_SNAKE_CASE						(      self      :		Tuple	)     ->					str:
							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase_=  TFCvtModel.from_pretrained(__UpperCAmelCase	)
													self.assertIsNotNone(__UpperCAmelCase	)



def 			__a	(       ) ->					str:






						'''simple docstring'''



						UpperCAmelCase_=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
						return image






@require_tf
@require_vision
class 						lowercase		(					unittest.TestCase):






	"""simple docstring"""


	@cached_property
	def     _SCREAMING_SNAKE_CASE						(      self      :		Optional[Any]	)     ->					Dict:
							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)




	@slow
	def     _SCREAMING_SNAKE_CASE						(      self      :		Optional[Any]	)     ->					List[str]:
							UpperCAmelCase_=  TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

							UpperCAmelCase_=  self.default_image_processor
							UpperCAmelCase_=  prepare_img()
							UpperCAmelCase_=  image_processor(images=__UpperCAmelCase		,    return_tensors="""tf"""	)

							# forward pass
							UpperCAmelCase_=  model(**__UpperCAmelCase	)

							# verify the logits
							UpperCAmelCase_=  tf.TensorShape((1, 1_000)	)
							self.assertEqual(outputs.logits.shape		,    __UpperCAmelCase	)

							UpperCAmelCase_=  tf.constant([0.9_285, 0.9_015, -0.3_150]	)
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()		,    __UpperCAmelCase		,    atol=1E-4	)	)








'''simple docstring'''






def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  Dict				       =''
   for ch in key:
      if ch == " " or ch not in key_no_dups and ch.isalpha():
         key_no_dups += ch
   return key_no_dups





def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       =[chr(i + 6_5				) for i in range(2_6				)]
   # Remove duplicate characters from key
   _UpperCAmelCase  :  Any				       =remove_duplicates(key.upper()				)
   _UpperCAmelCase  :  Optional[Any]				       =len(__lowerCamelCase				)
   # First fill cipher with key characters
   _UpperCAmelCase  :  List[Any]				       ={alphabet[i]: char for i, char in enumerate(__lowerCamelCase				)}
   # Then map remaining characters in alphabet to
   # the alphabet from the beginning
   for i in range(len(__lowerCamelCase				)			,       2_6				):
      _UpperCAmelCase  :  Union[str, Any]				       =alphabet[i - offset]
      # Ensure we are not mapping letters to letters previously mapped
      while char in key:
         offset -= 1
         _UpperCAmelCase  :  str				       =alphabet[i - offset]
      _UpperCAmelCase  :  Any				       =char
   return cipher_alphabet





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   return "".join(cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       ={v: k for k, v in cipher_map.items()}
   return "".join(rev_cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		):







   '''simple docstring'''




   _UpperCAmelCase  :  Union[str, Any]				       =input('Enter message to encode or decode: '				).strip()
   _UpperCAmelCase  :  int				       =input('Enter keyword: '				).strip()
   _UpperCAmelCase  :  int				       =input('Encipher or decipher? E/D:'				).strip()[0].lower()
   try:
      _UpperCAmelCase  :  Tuple				       ={'e': encipher, 'd': decipher}[option]
   except KeyError:
      raise KeyError('invalid input option'				)
   _UpperCAmelCase  :  List[str]				       =create_cipher_map(__lowerCamelCase				)
   print(func(__lowerCamelCase			,       __lowerCamelCase				)				)


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 main()

