



from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
						import tensorflow as tf


UpperCAmelCase__       =	logging.get_logger(__name__)







@dataclass
class       __lowerCAmelCase   (      SCREAMING_SNAKE_CASE__						):
			UpperCamelCase        =					[
			    '''no_inference''',
			    '''no_cuda''',
			    '''no_tpu''',
			    '''no_speed''',
			    '''no_memory''',
			    '''no_env_print''',
			    '''no_multi_process''',
			]



			def __init__(						self       :  Optional[int]			,		**A       :  List[Any])       ->   List[str]:



						"""simple docstring"""






						for deprecated_arg in self.deprecated_args:
									if deprecated_arg in kwargs:
												_UpperCAmelCase			=       deprecated_arg[3:]
												_UpperCAmelCase			=       not kwargs.pop(A__)
												logger.warning(
												    F"{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"
												    F" {positive_arg}={kwargs[positive_arg]}")
						_UpperCAmelCase			=       kwargs.pop('tpu_name'			,		self.tpu_name)
						_UpperCAmelCase			=       kwargs.pop('device_idx'			,		self.device_idx)
						_UpperCAmelCase			=       kwargs.pop('eager_mode'			,		self.eager_mode)
						_UpperCAmelCase			=       kwargs.pop('use_xla'			,		self.use_xla)
						super().__init__(**A__)

			UpperCamelCase        =					field(
			    default=SCREAMING_SNAKE_CASE__    ,						metadata={'''help''': '''Name of TPU'''}    ,						)
			UpperCamelCase        =					field(
			    default=0    ,						metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}    ,						)
			UpperCamelCase        =					field(default=SCREAMING_SNAKE_CASE__    ,						metadata={'''help''': '''Benchmark models in eager model.'''}						)
			UpperCamelCase        =					field(
			    default=SCREAMING_SNAKE_CASE__    ,						metadata={
			        '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
			    }    ,						)



			@cached_property
			def    _lowerCamelCase	(						self       :  Dict)       ->   Optional[Any]:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						_UpperCAmelCase			=       None
						if self.tpu:
									try:
												if self.tpu_name:
															_UpperCAmelCase			=       tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name)
												else:
															_UpperCAmelCase			=       tf.distribute.cluster_resolver.TPUClusterResolver()
									except ValueError:
												_UpperCAmelCase			=       None
						return tpu



			@cached_property
			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   Optional[int]:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						if self.is_tpu:
									tf.config.experimental_connect_to_cluster(self._setup_tpu)
									tf.tpu.experimental.initialize_tpu_system(self._setup_tpu)

									_UpperCAmelCase			=       tf.distribute.TPUStrategy(self._setup_tpu)
						else:
									# currently no multi gpu is allowed
									if self.is_gpu:
												# TODO: Currently only single GPU is supported
												tf.config.set_visible_devices(self.gpu_list[self.device_idx]			,		'GPU')
												_UpperCAmelCase			=       tf.distribute.OneDeviceStrategy(device=F"/gpu:{self.device_idx}")
									else:
												tf.config.set_visible_devices([]			,		'GPU')  # disable GPU
												_UpperCAmelCase			=       tf.distribute.OneDeviceStrategy(device=F"/cpu:{self.device_idx}")

						return strategy



			@property
			def    _lowerCamelCase	(						self       :  str)       ->   Optional[Any]:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						return self._setup_tpu is not None



			@property
			def    _lowerCamelCase	(						self       :  Dict)       ->   Any:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						return self._setup_strategy



			@property
			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Dict:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						return tf.config.list_physical_devices('GPU')



			@property
			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   str:



						"""simple docstring"""






						requires_backends(self			,		['tf'])
						if self.cuda:
									return len(self.gpu_list)
						return 0



			@property
			def    _lowerCamelCase	(						self       :  List[Any])       ->   Optional[Any]:



						"""simple docstring"""






						return self.n_gpu > 0





import string

import numpy





def 							A     (					_UpperCAmelCase    :       int							,       _UpperCAmelCase    :       int   )    ->			int:







			'''simple docstring'''
			return b if a == 0 else greatest_common_divisor(b % a							,       _UpperCAmelCase   )







class       __lowerCAmelCase   :
			UpperCamelCase        =					string.ascii_uppercase + string.digits
			# This cipher takes alphanumerics into account
			# i.e. a total of 36 characters

			# take x and return x % len(key_string)
			UpperCamelCase        =					numpy.vectorize(lambda A						: x % 3_6						)

			UpperCamelCase        =					numpy.vectorize(A						)



			def __init__(						self       :  Tuple			,		A       :  numpy.ndarray)       ->   None:



						"""simple docstring"""






						_UpperCAmelCase			=       self.modulus(A)  # mod36 calc's on the encrypt key
						self.check_determinant()  # validate the determinant of the encryption key
						_UpperCAmelCase			=       encrypt_key.shape[0]



			def    _lowerCamelCase	(						self       :  str			,		A       :  str)       ->   int:



						"""simple docstring"""






						return self.key_string.index(A)



			def    _lowerCamelCase	(						self       :  Any			,		A       :  int)       ->   str:



						"""simple docstring"""






						return self.key_string[round(A)]



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



						"""simple docstring"""






						_UpperCAmelCase			=       round(numpy.linalg.det(self.encrypt_key))

						if det < 0:
									_UpperCAmelCase			=       det % len(self.key_string)

						_UpperCAmelCase			=       len(self.key_string)
						if greatest_common_divisor(A			,		len(self.key_string)) != 1:
									_UpperCAmelCase			=       (
									    F"determinant modular {req_l} of encryption key({det}) "
									    F"is not co prime w.r.t {req_l}.\nTry another key."
									)
									raise ValueError(A)



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



						"""simple docstring"""






						_UpperCAmelCase			=       [char for char in text.upper() if char in self.key_string]

						_UpperCAmelCase			=       chars[-1]
						while len(A) % self.break_key != 0:
									chars.append(A)

						return "".join(A)



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



						"""simple docstring"""






						_UpperCAmelCase			=       self.process_text(text.upper())
						_UpperCAmelCase			=       ''

						for i in range(0			,		len(A) - self.break_key + 1			,		self.break_key):
									_UpperCAmelCase			=       text[i : i + self.break_key]
									_UpperCAmelCase			=       [self.replace_letters(A) for char in batch]
									_UpperCAmelCase			=       numpy.array([vec]).T
									_UpperCAmelCase			=       self.modulus(self.encrypt_key.dot(A)).T.tolist()[
									    0
									]
									_UpperCAmelCase			=       ''.join(
									    self.replace_digits(A) for num in batch_encrypted)
									encrypted += encrypted_batch

						return encrypted



			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   numpy.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       round(numpy.linalg.det(self.encrypt_key))

						if det < 0:
									_UpperCAmelCase			=       det % len(self.key_string)
						_UpperCAmelCase			=       None
						for i in range(len(self.key_string)):
									if (det * i) % len(self.key_string) == 1:
												_UpperCAmelCase			=       i
												break

						_UpperCAmelCase			=       (
						    det_inv
						    * numpy.linalg.det(self.encrypt_key)
						    * numpy.linalg.inv(self.encrypt_key)
						)

						return self.to_int(self.modulus(A))



			def    _lowerCamelCase	(						self       :  Tuple			,		A       :  str)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self.make_decrypt_key()
						_UpperCAmelCase			=       self.process_text(text.upper())
						_UpperCAmelCase			=       ''

						for i in range(0			,		len(A) - self.break_key + 1			,		self.break_key):
									_UpperCAmelCase			=       text[i : i + self.break_key]
									_UpperCAmelCase			=       [self.replace_letters(A) for char in batch]
									_UpperCAmelCase			=       numpy.array([vec]).T
									_UpperCAmelCase			=       self.modulus(decrypt_key.dot(A)).T.tolist()[0]
									_UpperCAmelCase			=       ''.join(
									    self.replace_digits(A) for num in batch_decrypted)
									decrypted += decrypted_batch

						return decrypted





def 							A     (					)    ->			None:







			'''simple docstring'''
			_UpperCAmelCase			=       int(input('Enter the order of the encryption key: '   )   )
			_UpperCAmelCase			=       []

			print('Enter each row of the encryption key with space separated integers'   )
			for _ in range(_UpperCAmelCase   ):
						_UpperCAmelCase			=       [int(_UpperCAmelCase   ) for x in input().split()]
						hill_matrix.append(_UpperCAmelCase   )

			_UpperCAmelCase			=       HillCipher(numpy.array(_UpperCAmelCase   )   )

			print('Would you like to encrypt or decrypt some text? (1 or 2)'   )
			_UpperCAmelCase			=       input('\n1. Encrypt\n2. Decrypt\n'   )
			if option == "1":
						_UpperCAmelCase			=       input('What text would you like to encrypt?: '   )
						print('Your encrypted text is:'   )
						print(hc.encrypt(_UpperCAmelCase   )   )
			elif option == "2":
						_UpperCAmelCase			=       input('What text would you like to decrypt?: '   )
						print('Your decrypted text is:'   )
						print(hc.decrypt(_UpperCAmelCase   )   )


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							main()
