import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
						from transformers.models.mobilevitva.modeling_mobilevitva import (
						    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
						    make_divisible,
						)


if is_vision_available():
						from PIL import Image

						from transformers import MobileViTImageProcessor






class      __lowercase					(    _A    ):

						def        __a		(	self				:      int   )							->		Tuple:


									'''simple docstring'''

									lowercase							=		self.config_class(**self.inputs_dict   )
									self.parent.assertTrue(hasattr(__lowerCamelCase							,							'''width_multiplier'''   )   )






class      __lowercase					:

						def __init__(	self				:      str							,							__lowerCamelCase				:      int							,							__lowerCamelCase				:      int=13							,							__lowerCamelCase				:      List[Any]=64							,							__lowerCamelCase				:      Tuple=2							,							__lowerCamelCase				:      Tuple=3							,							__lowerCamelCase				:      int="swish"							,							__lowerCamelCase				:      Optional[int]=3							,							__lowerCamelCase				:      str=32							,							__lowerCamelCase				:      List[str]=0.1							,							__lowerCamelCase				:      int=0.02							,							__lowerCamelCase				:      List[str]=True							,							__lowerCamelCase				:      Union[str, Any]=True							,							__lowerCamelCase				:      Optional[int]=10							,							__lowerCamelCase				:      Tuple=None							,							__lowerCamelCase				:      List[str]=0.25							,							__lowerCamelCase				:      Tuple=0.0							,							__lowerCamelCase				:      List[str]=0.0							,							)							->		Tuple:


									'''simple docstring'''

									lowercase							=		parent
									lowercase							=		batch_size
									lowercase							=		image_size
									lowercase							=		patch_size
									lowercase							=		num_channels
									lowercase							=		make_divisible(5_12 * width_multiplier							,							divisor=8   )
									lowercase							=		hidden_act
									lowercase							=		conv_kernel_size
									lowercase							=		output_stride
									lowercase							=		classifier_dropout_prob
									lowercase							=		use_labels
									lowercase							=		is_training
									lowercase							=		num_labels
									lowercase							=		initializer_range
									lowercase							=		scope
									lowercase							=		width_multiplier
									lowercase							=		ffn_dropout
									lowercase							=		attn_dropout

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


									'''simple docstring'''

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

									lowercase							=		None
									lowercase							=		None
									if self.use_labels:
												lowercase							=		ids_tensor([self.batch_size]							,							self.num_labels   )
												lowercase							=		ids_tensor([self.batch_size, self.image_size, self.image_size]							,							self.num_labels   )

									lowercase							=		self.get_config()

									return config, pixel_values, labels, pixel_labels

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


									'''simple docstring'''

									return MobileViTVaConfig(
									    image_size=self.image_size							,							patch_size=self.patch_size							,							num_channels=self.num_channels							,							hidden_act=self.hidden_act							,							conv_kernel_size=self.conv_kernel_size							,							output_stride=self.output_stride							,							classifier_dropout_prob=self.classifier_dropout_prob							,							initializer_range=self.initializer_range							,							width_multiplier=self.width_multiplier							,							ffn_dropout=self.ffn_dropout_prob							,							attn_dropout=self.attn_dropout_prob							,							)

						def        __a		(	self				:      List[str]							,							__lowerCamelCase				:      Tuple							,							__lowerCamelCase				:      Optional[Any]							,							__lowerCamelCase				:      Tuple							,							__lowerCamelCase				:      int   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		MobileViTVaModel(config=__lowerCamelCase   )
									model.to(__lowerCamelCase   )
									model.eval()
									lowercase							=		model(__lowerCamelCase   )
									self.parent.assertEqual(
									    result.last_hidden_state.shape							,							(
									        self.batch_size,
									        self.last_hidden_size,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )							,							)

						def        __a		(	self				:      int							,							__lowerCamelCase				:      str							,							__lowerCamelCase				:      str							,							__lowerCamelCase				:      List[str]							,							__lowerCamelCase				:      Optional[Any]   )							->		Optional[Any]:


									'''simple docstring'''

									lowercase							=		self.num_labels
									lowercase							=		MobileViTVaForImageClassification(__lowerCamelCase   )
									model.to(__lowerCamelCase   )
									model.eval()
									lowercase							=		model(__lowerCamelCase							,							labels=__lowerCamelCase   )
									self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.num_labels)   )

						def        __a		(	self				:      Union[str, Any]							,							__lowerCamelCase				:      List[str]							,							__lowerCamelCase				:      Dict							,							__lowerCamelCase				:      Optional[Any]							,							__lowerCamelCase				:      Any   )							->		str:


									'''simple docstring'''

									lowercase							=		self.num_labels
									lowercase							=		MobileViTVaForSemanticSegmentation(__lowerCamelCase   )
									model.to(__lowerCamelCase   )
									model.eval()
									lowercase							=		model(__lowerCamelCase   )
									self.parent.assertEqual(
									    result.logits.shape							,							(
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )							,							)
									lowercase							=		model(__lowerCamelCase							,							labels=__lowerCamelCase   )
									self.parent.assertEqual(
									    result.logits.shape							,							(
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )							,							)



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


									'''simple docstring'''

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






@require_torch
class      __lowercase					(    _A       ,     _A       ,     unittest.TestCase    ):
						lowercase					 =     (
						    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)

						lowercase					 =     (
						    {
						        'feature-extraction': MobileViTVaModel,
						        'image-classification': MobileViTVaForImageClassification,
						        'image-segmentation': MobileViTVaForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						lowercase					 =     False
						lowercase					 =     False
						lowercase					 =     False
						lowercase					 =     False

						def        __a		(	self				:      str   )							->		Optional[int]:


									'''simple docstring'''

									lowercase							=		MobileViTVaModelTester(self   )
									lowercase							=		MobileViTVaConfigTester(self							,							config_class=__lowerCamelCase							,							has_text_modality=__lowerCamelCase   )

						def        __a		(	self				:      Tuple   )							->		str:


									'''simple docstring'''

									self.config_tester.run_common_tests()

						@unittest.skip(reason='''MobileViTV2 does not use inputs_embeds'''   )
						def        __a		(	self				:      int   )							->		List[str]:


									'''simple docstring'''

									pass

						@unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''   )
						def        __a		(	self				:      str   )							->		Tuple:


									'''simple docstring'''

									pass

						@unittest.skip(reason='''MobileViTV2 does not output attentions'''   )
						def        __a		(	self				:      Union[str, Any]   )							->		Any:


									'''simple docstring'''

									pass

						@require_torch_multi_gpu
						@unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.'''   )
						def        __a		(	self				:      str   )							->		Dict:


									'''simple docstring'''

									pass

						@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
						def        __a		(	self				:      Union[str, Any]   )							->		Tuple:


									'''simple docstring'''

									pass

						def        __a		(	self				:      str   )							->		Dict:


									'''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.forward   )
												# 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        __a		(	self				:      List[str]   )							->		Optional[Any]:


									'''simple docstring'''

									lowercase							=		self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase   )

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


									'''simple docstring'''

									def check_hidden_states_output(__lowerCamelCase				:      Any							,							__lowerCamelCase				:      List[Any]							,							__lowerCamelCase				:      Union[str, Any]   ):
												lowercase							=		model_class(__lowerCamelCase   )
												model.to(__lowerCamelCase   )
												model.eval()

												with torch.no_grad():
															lowercase							=		model(**self._prepare_for_class(__lowerCamelCase							,							__lowerCamelCase   )   )

												lowercase							=		outputs.hidden_states

												lowercase							=		5
												self.assertEqual(len(__lowerCamelCase   )							,							__lowerCamelCase   )

												# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
												# with the width and height being successively divided by 2.
												lowercase							=		2
												for i in range(len(__lowerCamelCase   )   ):
															self.assertListEqual(
															    list(hidden_states[i].shape[-2:]   )							,							[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]							,							)
															divisor *= 2

												self.assertEqual(self.model_tester.output_stride							,							divisor // 2   )

									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        __a		(	self				:      List[str]   )							->		List[str]:


									'''simple docstring'''

									lowercase							=		self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase   )

						def        __a		(	self				:      Optional[Any]   )							->		Tuple:


									'''simple docstring'''

									lowercase							=		self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase   )



						@slow
						def        __a		(	self				:      List[Any]   )							->		List[Any]:


									'''simple docstring'''

									for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												lowercase							=		MobileViTVaModel.from_pretrained(__lowerCamelCase   )
												self.assertIsNotNone(__lowerCamelCase   )






def        __UpperCAmelCase    (       )->       Optional[int]:



			"""simple docstring"""







			lowercase							=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
			return image






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

						@cached_property
						def        __a		(	self				:      int   )							->		Tuple:


									'''simple docstring'''

									return (
									    MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''   )
									    if is_vision_available()
									    else None
									)

						@slow
						def        __a		(	self				:      Optional[Any]   )							->		Dict:


									'''simple docstring'''

									lowercase							=		MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''   ).to(
									    __lowerCamelCase   )

									lowercase							=		self.default_image_processor
									lowercase							=		prepare_img()
									lowercase							=		image_processor(images=__lowerCamelCase							,							return_tensors='''pt'''   ).to(__lowerCamelCase   )

									# forward pass
									with torch.no_grad():
												lowercase							=		model(**__lowerCamelCase   )

									# verify the logits
									lowercase							=		torch.Size((1, 10_00)   )
									self.assertEqual(outputs.logits.shape							,							__lowerCamelCase   )

									lowercase							=		torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]   ).to(__lowerCamelCase   )

									self.assertTrue(torch.allclose(outputs.logits[0, :3]							,							__lowerCamelCase							,							atol=1E-4   )   )

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


									'''simple docstring'''

									lowercase							=		MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )
									lowercase							=		model.to(__lowerCamelCase   )

									lowercase							=		MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )

									lowercase							=		prepare_img()
									lowercase							=		image_processor(images=__lowerCamelCase							,							return_tensors='''pt'''   ).to(__lowerCamelCase   )

									# forward pass
									with torch.no_grad():
												lowercase							=		model(**__lowerCamelCase   )
									lowercase							=		outputs.logits

									# verify the logits
									lowercase							=		torch.Size((1, 21, 32, 32)   )
									self.assertEqual(logits.shape							,							__lowerCamelCase   )

									lowercase							=		torch.tensor(
									    [
									        [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
									        [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
									        [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
									    ]							,							device=__lowerCamelCase							,							)

									self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,							__lowerCamelCase							,							atol=1E-4   )   )



						@slow
						def        __a		(	self				:      Union[str, Any]   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )
									lowercase							=		model.to(__lowerCamelCase   )

									lowercase							=		MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''   )

									lowercase							=		prepare_img()
									lowercase							=		image_processor(images=__lowerCamelCase							,							return_tensors='''pt'''   ).to(__lowerCamelCase   )

									# forward pass
									with torch.no_grad():
												lowercase							=		model(**__lowerCamelCase   )

									lowercase							=		outputs.logits.detach().cpu()

									lowercase							=		image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase							,							target_sizes=[(50, 60)]   )
									lowercase							=		torch.Size((50, 60)   )
									self.assertEqual(segmentation[0].shape							,							__lowerCamelCase   )

									lowercase							=		image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase   )
									lowercase							=		torch.Size((32, 32)   )
									self.assertEqual(segmentation[0].shape							,							__lowerCamelCase   )






import os
import random
import sys

from . import cryptomath_module as cryptomath
from . import rabin_miller

A_      =      3






def        __UpperCAmelCase    (       UpperCAmelCase       )->       int:



			"""simple docstring"""







			print('''Generating primitive root of p'''       )
			while True:
						lowercase							=		random.randrange(3,		UpperCAmelCase       )
						if pow(UpperCAmelCase,		2,		UpperCAmelCase       ) == 1:
									continue
						if pow(UpperCAmelCase,		UpperCAmelCase,		UpperCAmelCase       ) == 1:
									continue
						return g






def        __UpperCAmelCase    (       UpperCAmelCase       )->       tuple[tuple[int, int, int, int], tuple[int, int]]:



			"""simple docstring"""







			print('''Generating prime p...'''       )
			lowercase							=		rabin_miller.generate_large_prime(UpperCAmelCase       )  # select large prime number.
			lowercase							=		primitive_root(UpperCAmelCase       )  # one primitive root on modulo p.
			lowercase							=		random.randrange(3,		UpperCAmelCase       )  # private_key -> have to be greater than 2 for safety.
			lowercase							=		cryptomath.find_mod_inverse(pow(UpperCAmelCase,		UpperCAmelCase,		UpperCAmelCase       ),		UpperCAmelCase       )

			lowercase							=		(key_size, e_a, e_a, p)
			lowercase							=		(key_size, d)

			return public_key, private_key






def        __UpperCAmelCase    (       UpperCAmelCase,		UpperCAmelCase       )->       None:



			"""simple docstring"""







			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(UpperCAmelCase       )
			print(f'\nWriting public key to file {name}_pubkey.txt...'       )
			with open(f'{name}_pubkey.txt',		'''w'''       ) as fo:
						fo.write(f'{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}'       )

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






def        __UpperCAmelCase    (       )->       None:



			"""simple docstring"""







			print('''Making key files...'''       )
			make_key_files('''elgamal''',		2048       )
			print('''Key files generation successful'''       )


if __name__ == "__main__":
						main()





