





'''simple docstring'''



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    ( lowerCAmelCase__  ):







	'''simple docstring'''

	def   _UpperCAmelCase       (self	)							->							int:







				'''simple docstring'''





				__lowercase			  =							self.config_class(**self.inputs_dict	)
				self.parent.assertTrue(hasattr(_lowerCamelCase       ,'''embed_dim'''	)	)
				self.parent.assertTrue(hasattr(_lowerCamelCase       ,'''num_heads'''	)	)






class 							__lowercase    :







	'''simple docstring'''

	def __init__(self       ,_lowerCamelCase       ,_lowerCamelCase=13       ,_lowerCamelCase=64       ,_lowerCamelCase=3       ,_lowerCamelCase=[16, 48, 96]       ,_lowerCamelCase=[1, 3, 6]       ,_lowerCamelCase=[1, 2, 10]       ,_lowerCamelCase=[7, 3, 3]       ,_lowerCamelCase=[4, 2, 2]       ,_lowerCamelCase=[2, 1, 1]       ,_lowerCamelCase=[2, 2, 2]       ,_lowerCamelCase=[False, False, True]       ,_lowerCamelCase=[0.0, 0.0, 0.0]       ,_lowerCamelCase=0.0_2       ,_lowerCamelCase=1E-1_2       ,_lowerCamelCase=True       ,_lowerCamelCase=True       ,_lowerCamelCase=2       ,)							->							List[str]:







				'''simple docstring'''





				__lowercase			  =							parent
				__lowercase			  =							batch_size
				__lowercase			  =							image_size
				__lowercase			  =							patch_sizes
				__lowercase			  =							patch_stride
				__lowercase			  =							patch_padding
				__lowercase			  =							is_training
				__lowercase			  =							use_labels
				__lowercase			  =							num_labels
				__lowercase			  =							num_channels
				__lowercase			  =							embed_dim
				__lowercase			  =							num_heads
				__lowercase			  =							stride_kv
				__lowercase			  =							depth
				__lowercase			  =							cls_token
				__lowercase			  =							attention_drop_rate
				__lowercase			  =							initializer_range
				__lowercase			  =							layer_norm_eps


	def   _UpperCAmelCase       (self	)							->							str:







				'''simple docstring'''





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

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

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


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







				'''simple docstring'''





				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   _UpperCAmelCase       (self       ,_lowerCamelCase       ,_lowerCamelCase       ,_lowerCamelCase	)							->							int:







				'''simple docstring'''





				__lowercase			  =							TFCvtModel(config=_lowerCamelCase	)
				__lowercase			  =							model(_lowerCamelCase       ,training=_lowerCamelCase	)
				__lowercase			  =							(self.image_size, self.image_size)
				__lowercase  ,						__lowercase			  =							image_size[0], image_size[1]
				for i in range(len(self.depth	)	):
							__lowercase			  =							floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
							__lowercase			  =							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   _UpperCAmelCase       (self       ,_lowerCamelCase       ,_lowerCamelCase       ,_lowerCamelCase	)							->							Union[str, Any]:







				'''simple docstring'''





				__lowercase			  =							self.num_labels
				__lowercase			  =							TFCvtForImageClassification(_lowerCamelCase	)
				__lowercase			  =							model(_lowerCamelCase       ,labels=_lowerCamelCase       ,training=_lowerCamelCase	)
				self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)	)


	def   _UpperCAmelCase       (self	)							->							Tuple:







				'''simple docstring'''





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






@require_tf
class 							__lowercase    ( lowerCAmelCase__	, lowerCAmelCase__	, unittest.TestCase  ):







	'''simple docstring'''

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


	def   _UpperCAmelCase       (self	)							->							Optional[Any]:







				'''simple docstring'''





				__lowercase			  =							TFCvtModelTester(self	)
				__lowercase			  =							TFCvtConfigTester(self       ,config_class=_lowerCamelCase       ,has_text_modality=_lowerCamelCase       ,hidden_size=37	)


	def   _UpperCAmelCase       (self	)							->							int:







				'''simple docstring'''





				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   _UpperCAmelCase       (self	)							->							Optional[int]:







				'''simple docstring'''





				pass


	@unittest.skip(reason='''Cvt does not use inputs_embeds'''	)
	def   _UpperCAmelCase       (self	)							->							Optional[int]:







				'''simple docstring'''





				pass


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







				'''simple docstring'''





				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   _UpperCAmelCase       (self	)							->							Tuple:







				'''simple docstring'''





				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   _UpperCAmelCase       (self	)							->							Union[str, Any]:







				'''simple docstring'''





				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   _UpperCAmelCase       (self	)							->							Optional[int]:







				'''simple docstring'''





				__lowercase			  =							tf.keras.mixed_precision.Policy('''mixed_float16'''	)
				tf.keras.mixed_precision.set_global_policy(_lowerCamelCase	)
				super().test_keras_fit()
				tf.keras.mixed_precision.set_global_policy('''float32'''	)


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







				'''simple docstring'''





				__lowercase  ,						__lowercase			  =							self.model_tester.prepare_config_and_inputs_for_common()

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

							__lowercase			  =							['''pixel_values''']
							self.assertListEqual(arg_names[:1]       ,_lowerCamelCase	)


	def   _UpperCAmelCase       (self	)							->							Any:







				'''simple docstring'''





				def check_hidden_states_output(_lowerCamelCase       ,_lowerCamelCase       ,_lowerCamelCase	):
							__lowercase			  =							model_class(_lowerCamelCase	)

							__lowercase			  =							model(**self._prepare_for_class(_lowerCamelCase       ,_lowerCamelCase	)	)
							__lowercase			  =							outputs.hidden_states

							__lowercase			  =							len(self.model_tester.depth	)
							self.assertEqual(len(_lowerCamelCase	)       ,_lowerCamelCase	)

							# 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,
							    ]       ,)

				__lowercase  ,						__lowercase			  =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							__lowercase			  =							True
							check_hidden_states_output(_lowerCamelCase       ,_lowerCamelCase       ,_lowerCamelCase	)

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

							check_hidden_states_output(_lowerCamelCase       ,_lowerCamelCase       ,_lowerCamelCase	)


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







				'''simple docstring'''





				__lowercase			  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_lowerCamelCase	)


	def   _UpperCAmelCase       (self	)							->							Any:







				'''simple docstring'''





				__lowercase			  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase	)


	@slow
	def   _UpperCAmelCase       (self	)							->							int:







				'''simple docstring'''





				for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowercase			  =							TFCvtModel.from_pretrained(_lowerCamelCase	)
							self.assertIsNotNone(_lowerCamelCase	)





def 				_lowerCAmelCase  (			):
			__lowercase			  =							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
			return image






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







	'''simple docstring'''

	@cached_property
	def   _UpperCAmelCase       (self	)							->							Any:







				'''simple docstring'''





				return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)


	@slow
	def   _UpperCAmelCase       (self	)							->							Optional[int]:







				'''simple docstring'''





				__lowercase			  =							TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

				__lowercase			  =							self.default_image_processor
				__lowercase			  =							prepare_img()
				__lowercase			  =							image_processor(images=_lowerCamelCase       ,return_tensors='''tf'''	)

				# forward pass
				__lowercase			  =							model(**_lowerCamelCase	)

				# verify the logits
				__lowercase			  =							tf.TensorShape((1, 1000)	)
				self.assertEqual(outputs.logits.shape       ,_lowerCamelCase	)

				__lowercase			  =							tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]	)
				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,_lowerCamelCase       ,atol=1E-4	)	)












'''simple docstring'''



import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812




def 				_lowerCAmelCase  (			):
			print('''Making key files...'''			)
			make_key_files('''rsa'''						,    1_0_2_4			)
			print('''Key files generation successful.'''			)




def 				_lowerCAmelCase  (			lowerCamelCase_     :					int			):
			print('''Generating prime p...'''			)
			__lowercase			  =							rabinMiller.generate_large_prime(lowerCamelCase_			)
			print('''Generating prime q...'''			)
			__lowercase			  =							rabinMiller.generate_large_prime(lowerCamelCase_			)
			__lowercase			  =							p * q

			print('''Generating e that is relatively prime to (p - 1) * (q - 1)...'''			)
			while True:
						__lowercase			  =							random.randrange(2 ** (key_size - 1)						,    2 ** (key_size)			)
						if cryptoMath.gcd(lowerCamelCase_						,    (p - 1) * (q - 1)			) == 1:
									break

			print('''Calculating d that is mod inverse of e...'''			)
			__lowercase			  =							cryptoMath.find_mod_inverse(lowerCamelCase_						,    (p - 1) * (q - 1)			)

			__lowercase			  =							(n, e)
			__lowercase			  =							(n, d)
			return (public_key, private_key)




def 				_lowerCAmelCase  (			lowerCamelCase_     :					str						,    lowerCamelCase_     :					int			):
			if os.path.exists(f"{name}_pubkey.txt"			) or os.path.exists(f"{name}_privkey.txt"			):
						print('''\nWARNING:'''			)
						print(
						    f"\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"
						    '''Use a different name or delete these files and re-run this program.'''			)
						sys.exit()

			__lowercase  ,						__lowercase			  =							generate_key(lowerCamelCase_			)
			print(f"\nWriting public key to file {name}_pubkey.txt..."			)
			with open(f"{name}_pubkey.txt"						,    '''w'''			) as out_file:
						out_file.write(f"{key_size},{public_key[0]},{public_key[1]}"			)

			print(f"Writing private key to file {name}_privkey.txt..."			)
			with open(f"{name}_privkey.txt"						,    '''w'''			) as out_file:
						out_file.write(f"{key_size},{private_key[0]},{private_key[1]}"			)


if __name__ == "__main__":
	main()





