


'''simple docstring'''







import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import (
		    MODEL_MAPPING,
		    DataaVecVisionForImageClassification,
		    DataaVecVisionForSemanticSegmentation,
		    DataaVecVisionModel,
		)
		from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import BeitImageProcessor






class 		_snake_case    :






						'''simple docstring'''







						def __init__(  self:	Tuple      ,							__UpperCamelCase:	List[Any]      ,							__UpperCamelCase:	Any=100      ,							__UpperCamelCase:	Tuple=13      ,							__UpperCamelCase:	Union[str, Any]=30      ,							__UpperCamelCase:	Any=2      ,							__UpperCamelCase:	Union[str, Any]=3      ,							__UpperCamelCase:	List[Any]=True      ,							__UpperCamelCase:	int=True      ,							__UpperCamelCase:	Optional[int]=32      ,							__UpperCamelCase:	List[Any]=4      ,							__UpperCamelCase:	int=4      ,							__UpperCamelCase:	int=37      ,							__UpperCamelCase:	int="gelu"      ,							__UpperCamelCase:	Optional[Any]=0.1      ,							__UpperCamelCase:	Tuple=0.1      ,							__UpperCamelCase:	List[str]=10      ,							__UpperCamelCase:	Any=0.0_2      ,							__UpperCamelCase:	Union[str, Any]=3      ,							__UpperCamelCase:	Optional[Any]=None      ,							__UpperCamelCase:	str=[0, 1, 2, 3]      ,							)							->	Tuple:
										__magic_name__				:					Union[str, Any]						       =       parent
										__magic_name__				:					List[Any]						       =       100
										__magic_name__				:					Optional[Any]						       =       batch_size
										__magic_name__				:					Optional[Any]						       =       image_size
										__magic_name__				:					List[str]						       =       patch_size
										__magic_name__				:					Any						       =       num_channels
										__magic_name__				:					Optional[Any]						       =       is_training
										__magic_name__				:					Optional[Any]						       =       use_labels
										__magic_name__				:					str						       =       hidden_size
										__magic_name__				:					List[str]						       =       num_hidden_layers
										__magic_name__				:					str						       =       num_attention_heads
										__magic_name__				:					List[Any]						       =       intermediate_size
										__magic_name__				:					Optional[int]						       =       hidden_act
										__magic_name__				:					Any						       =       hidden_dropout_prob
										__magic_name__				:					int						       =       attention_probs_dropout_prob
										__magic_name__				:					str						       =       type_sequence_label_size
										__magic_name__				:					Tuple						       =       initializer_range
										__magic_name__				:					str						       =       scope
										__magic_name__				:					Union[str, Any]						       =       out_indices
										__magic_name__				:					Optional[int]						       =       num_labels

										# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										__magic_name__				:					str						       =       (image_size // patch_size) ** 2
										__magic_name__				:					Dict						       =       num_patches + 1







						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Any:
										__magic_name__				:					Optional[int]						       =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

										__magic_name__				:					int						       =       None
										__magic_name__				:					Any						       =       None
										if self.use_labels:
														__magic_name__				:					Tuple						       =       ids_tensor([self.batch_size]      ,							self.type_sequence_label_size     )
														__magic_name__				:					Tuple						       =       ids_tensor([self.batch_size, self.image_size, self.image_size]      ,							self.num_labels     )

										__magic_name__				:					Any						       =       self.get_config()

										return config, pixel_values, labels, pixel_labels







						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Optional[int]:
										return DataaVecVisionConfig(
										    vocab_size=self.vocab_size      ,							image_size=self.image_size      ,							patch_size=self.patch_size      ,							num_channels=self.num_channels      ,							hidden_size=self.hidden_size      ,							num_hidden_layers=self.num_hidden_layers      ,							num_attention_heads=self.num_attention_heads      ,							intermediate_size=self.intermediate_size      ,							hidden_act=self.hidden_act      ,							hidden_dropout_prob=self.hidden_dropout_prob      ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,							is_decoder=__UpperCamelCase      ,							initializer_range=self.initializer_range      ,							out_indices=self.out_indices      ,							)







						def lowerCAmelCase__ (  self:	List[str]      ,							__UpperCamelCase:	List[Any]      ,							__UpperCamelCase:	Union[str, Any]      ,							__UpperCamelCase:	Optional[Any]      ,							__UpperCamelCase:	List[str]     )							->	Dict:
										__magic_name__				:					Any						       =       DataaVecVisionModel(config=__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					str						       =       model(__UpperCamelCase     )
										# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
										__magic_name__				:					Union[str, Any]						       =       (self.image_size // self.patch_size) ** 2
										self.parent.assertEqual(result.last_hidden_state.shape      ,							(self.batch_size, num_patches + 1, self.hidden_size)     )







						def lowerCAmelCase__ (  self:	Any      ,							__UpperCamelCase:	Any      ,							__UpperCamelCase:	Optional[Any]      ,							__UpperCamelCase:	Optional[int]      ,							__UpperCamelCase:	Union[str, Any]     )							->	List[str]:
										__magic_name__				:					List[str]						       =       self.type_sequence_label_size
										__magic_name__				:					Optional[int]						       =       DataaVecVisionForImageClassification(__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					Tuple						       =       model(__UpperCamelCase      ,							labels=__UpperCamelCase     )
										self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.type_sequence_label_size)     )







						def lowerCAmelCase__ (  self:	List[str]      ,							__UpperCamelCase:	Optional[Any]      ,							__UpperCamelCase:	Union[str, Any]      ,							__UpperCamelCase:	Optional[int]      ,							__UpperCamelCase:	str     )							->	Union[str, Any]:
										__magic_name__				:					Tuple						       =       self.num_labels
										__magic_name__				:					str						       =       DataaVecVisionForSemanticSegmentation(__UpperCamelCase     )
										model.to(__UpperCamelCase     )
										model.eval()
										__magic_name__				:					List[Any]						       =       model(__UpperCamelCase     )
										self.parent.assertEqual(
										    result.logits.shape      ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )
										__magic_name__				:					Tuple						       =       model(__UpperCamelCase      ,							labels=__UpperCamelCase     )
										self.parent.assertEqual(
										    result.logits.shape      ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )







						def lowerCAmelCase__ (  self:	Tuple     )							->	List[Any]:
										__magic_name__				:					Union[str, Any]						       =       self.prepare_config_and_inputs()
										__magic_name__       ,     __magic_name__       ,     __magic_name__       ,     __magic_name__				:					str						       =       config_and_inputs
										__magic_name__				:					int						       =       {"pixel_values": pixel_values}
										return config, inputs_dict






@require_torch
class 		_snake_case    (				snake_case_  ,  snake_case_  ,  unittest.TestCase		):






						'''simple docstring'''







						__snake_case   =      (
						    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						__snake_case   =      (
						    {
						        "feature-extraction": DataaVecVisionModel,
						        "image-classification": DataaVecVisionForImageClassification,
						        "image-segmentation": DataaVecVisionForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						__snake_case   =      False
						__snake_case   =      False
						__snake_case   =      False







						def lowerCAmelCase__ (  self:	Any     )							->	Optional[int]:
										__magic_name__				:					Optional[int]						       =       DataaVecVisionModelTester(self     )
										__magic_name__				:					List[Any]						       =       ConfigTester(
										    self      ,							config_class=__UpperCamelCase      ,							has_text_modality=__UpperCamelCase      ,							hidden_size=37     )







						def lowerCAmelCase__ (  self:	str     )							->	str:
										self.config_tester.run_common_tests()







						def lowerCAmelCase__ (  self:	int     )							->	Optional[int]:
										# Data2VecVision does not use inputs_embeds
										pass







						@require_torch_multi_gpu
						@unittest.skip(
						    reason="Data2VecVision has some layers using `add_module` which doesn't work well with `nn.DataParallel`"     )
						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Tuple:
										pass







						def lowerCAmelCase__ (  self:	List[Any]     )							->	Optional[int]:
										__magic_name__       ,     __magic_name__				:					Union[str, Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														__magic_name__				:					Any						       =       model_class(__UpperCamelCase     )
														self.assertIsInstance(model.get_input_embeddings()      ,							(nn.Module)     )
														__magic_name__				:					Union[str, Any]						       =       model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(__UpperCamelCase      ,							nn.Linear     )     )







						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Union[str, Any]:
										__magic_name__       ,     __magic_name__				:					Optional[Any]						       =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														__magic_name__				:					int						       =       model_class(__UpperCamelCase     )
														__magic_name__				:					List[Any]						       =       inspect.signature(model.forward     )
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														__magic_name__				:					Union[str, Any]						       =       [*signature.parameters.keys()]

														__magic_name__				:					List[Any]						       =       ["pixel_values"]
														self.assertListEqual(arg_names[:1]      ,							__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	Dict     )							->	Union[str, Any]:
										__magic_name__				:					Optional[int]						       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	List[str]     )							->	Optional[Any]:
										__magic_name__				:					Union[str, Any]						       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_segmentation(*__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	Dict     )							->	List[Any]:
										if not self.model_tester.is_training:
														return

										__magic_name__       ,     __magic_name__				:					Any						       =       self.model_tester.prepare_config_and_inputs_for_common()
										__magic_name__				:					List[str]						       =       True

										for model_class in self.all_model_classes:
														if model_class in [*get_values(__UpperCamelCase     )]:
																		continue

														__magic_name__				:					Tuple						       =       model_class(__UpperCamelCase     )
														model.to(__UpperCamelCase     )
														model.train()
														__magic_name__				:					Tuple						       =       self._prepare_for_class(__UpperCamelCase      ,							__UpperCamelCase      ,							return_labels=__UpperCamelCase     )
														__magic_name__				:					Optional[int]						       =       model(**__UpperCamelCase     ).loss
														loss.backward()







						def lowerCAmelCase__ (  self:	List[str]     )							->	Any:
										__magic_name__       ,     __magic_name__				:					str						       =       self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
														return

										__magic_name__				:					Dict						       =       False
										__magic_name__				:					Optional[int]						       =       True

										for model_class in self.all_model_classes:
														if model_class in [*get_values(__UpperCamelCase     )] or not model_class.supports_gradient_checkpointing:
																		continue
														# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
														# this can then be incorporated into _prepare_for_class in test_modeling_common.py
														elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
																		__magic_name__       ,     __magic_name__       ,     __magic_name__       ,     __magic_name__				:					List[str]						       =       inputs_dict["pixel_values"].shape
																		__magic_name__				:					Any						       =       torch.zeros(
																		    [self.model_tester.batch_size, height, width]      ,							device=__UpperCamelCase     ).long()
														__magic_name__				:					Optional[int]						       =       model_class(__UpperCamelCase     )
														model.gradient_checkpointing_enable()
														model.to(__UpperCamelCase     )
														model.train()
														__magic_name__				:					int						       =       self._prepare_for_class(__UpperCamelCase      ,							__UpperCamelCase      ,							return_labels=__UpperCamelCase     )
														__magic_name__				:					str						       =       model(**__UpperCamelCase     ).loss
														loss.backward()







						def lowerCAmelCase__ (  self:	Optional[Any]     )							->	Union[str, Any]:
										__magic_name__       ,     __magic_name__				:					List[str]						       =       self.model_tester.prepare_config_and_inputs_for_common()

										__magic_name__				:					Union[str, Any]						       =       _config_zero_init(__UpperCamelCase     )
										for model_class in self.all_model_classes:
														__magic_name__				:					Tuple						       =       model_class(config=__UpperCamelCase     )
														for name, param in model.named_parameters():
																		# we skip lambda parameters as these require special initial values
																		# determined by config.layer_scale_init_value
																		if "lambda" in name:
																						continue
																		if param.requires_grad:
																						self.assertIn(
																						    ((param.data.mean() * 1E9).round() / 1E9).item()      ,							[0.0, 1.0]      ,							msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""      ,							)







						def lowerCAmelCase__ (  self:	List[Any]      ,							__UpperCamelCase:	int      ,							__UpperCamelCase:	Union[str, Any]      ,							__UpperCamelCase:	Any      ,							__UpperCamelCase:	Optional[int]=2E-4      ,							__UpperCamelCase:	List[Any]="outputs"      ,							__UpperCamelCase:	Optional[int]=None     )							->	Tuple:
										# We override with a slightly higher tol value, as semseg models tend to diverge a bit more
										super().check_pt_tf_outputs(__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase     )







						def lowerCAmelCase__ (  self:	Tuple     )							->	Optional[int]:
										__magic_name__				:					str						       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase     )







						@slow
						def lowerCAmelCase__ (  self:	Dict     )							->	Dict:
										for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__magic_name__				:					Union[str, Any]						       =       DataaVecVisionModel.from_pretrained(__UpperCamelCase     )
														self.assertIsNotNone(__UpperCamelCase     )






def 						_UpperCamelCase							( ):






				"""simple docstring"""



				__magic_name__				:					Optional[Any]						       =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
				return image






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






						'''simple docstring'''







						@cached_property
						def lowerCAmelCase__ (  self:	Optional[int]     )							->	List[Any]:
										return (
										    BeitImageProcessor.from_pretrained("facebook/data2vec-vision-base-ft1k"     ) if is_vision_available() else None
										)







						@slow
						def lowerCAmelCase__ (  self:	Union[str, Any]     )							->	Dict:
										__magic_name__				:					Tuple						       =       DataaVecVisionForImageClassification.from_pretrained("facebook/data2vec-vision-base-ft1k"     ).to(
										    __UpperCamelCase     )

										__magic_name__				:					Optional[int]						       =       self.default_image_processor
										__magic_name__				:					Any						       =       prepare_img()
										__magic_name__				:					Optional[int]						       =       image_processor(images=__UpperCamelCase      ,							return_tensors="pt"     ).to(__UpperCamelCase     )

										# forward pass
										with torch.no_grad():
														__magic_name__				:					Tuple						       =       model(**__UpperCamelCase     )
										__magic_name__				:					Optional[Any]						       =       outputs.logits

										# verify the logits
										__magic_name__				:					List[str]						       =       torch.Size((1, 1000)     )
										self.assertEqual(logits.shape      ,							__UpperCamelCase     )

										__magic_name__				:					Tuple						       =       torch.tensor([0.3_2_7_7, -0.1_3_9_5, 0.0_9_1_1]     ).to(__UpperCamelCase     )

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

										__magic_name__				:					Dict						       =       [model.config.labelaid[i] for i in ["remote control, remote", "tabby, tabby cat"]]
										self.assertEqual(logits[0].topk(2     ).indices.cpu().tolist()      ,							__UpperCamelCase     )



'''simple docstring'''







def 						_UpperCamelCase							( UpperCamelCase__     ,   UpperCamelCase__		):






				"""simple docstring"""



				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("plaintext must be a string"		)
				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("key must be a string"		)

				if not plaintext:
								raise ValueError("plaintext is empty"		)
				if not key:
								raise ValueError("key is empty"		)

				key += plaintext
				__magic_name__				:					List[str]						       =       plaintext.lower()
				__magic_name__				:					Tuple						       =       key.lower()
				__magic_name__				:					Dict						       =       0
				__magic_name__				:					Optional[int]						       =       0
				__magic_name__				:					List[str]						       =       ""
				while plaintext_iterator < len(UpperCamelCase__		):
								if (
								    ord(plaintext[plaintext_iterator]		) < 97
								    or ord(plaintext[plaintext_iterator]		) > 122
								):
												ciphertext += plaintext[plaintext_iterator]
												plaintext_iterator += 1
								elif ord(key[key_iterator]		) < 97 or ord(key[key_iterator]		) > 122:
												key_iterator += 1
								else:
												ciphertext += chr(
												    (
												        (ord(plaintext[plaintext_iterator]		) - 97 + ord(key[key_iterator]		))
												        - 97
												    )
												    % 26
												    + 97		)
												key_iterator += 1
												plaintext_iterator += 1
				return ciphertext



def 						_UpperCamelCase							( UpperCamelCase__     ,   UpperCamelCase__		):






				"""simple docstring"""



				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("ciphertext must be a string"		)
				if not isinstance(UpperCamelCase__     ,   UpperCamelCase__		):
								raise TypeError("key must be a string"		)

				if not ciphertext:
								raise ValueError("ciphertext is empty"		)
				if not key:
								raise ValueError("key is empty"		)

				__magic_name__				:					List[str]						       =       key.lower()
				__magic_name__				:					str						       =       0
				__magic_name__				:					Optional[Any]						       =       0
				__magic_name__				:					Tuple						       =       ""
				while ciphertext_iterator < len(UpperCamelCase__		):
								if (
								    ord(ciphertext[ciphertext_iterator]		) < 97
								    or ord(ciphertext[ciphertext_iterator]		) > 122
								):
												plaintext += ciphertext[ciphertext_iterator]
								else:
												plaintext += chr(
												    (ord(ciphertext[ciphertext_iterator]		) - ord(key[key_iterator]		)) % 26
												    + 97		)
												key += chr(
												    (ord(ciphertext[ciphertext_iterator]		) - ord(key[key_iterator]		)) % 26
												    + 97		)
												key_iterator += 1
								ciphertext_iterator += 1
				return plaintext


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		_SCREAMING_SNAKE_CASE       :   Tuple        = int(input("Type 1 to encrypt or 2 to decrypt:"))
		if operation == 1:
				_SCREAMING_SNAKE_CASE       :   Optional[Any]        = input("Typeplaintext to be encrypted:\n")
				_SCREAMING_SNAKE_CASE       :   Tuple        = input("Type the key:\n")
				print(encrypt(plaintext, key))
		elif operation == 2:
				_SCREAMING_SNAKE_CASE       :   Optional[Any]        = input("Type the ciphertext to be decrypted:\n")
				_SCREAMING_SNAKE_CASE       :   List[str]        = input("Type the key:\n")
				print(decrypt(ciphertext, key))
		decrypt("jsqqs avvwo", "coffee")