



from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch







@require_torch
@require_tf
class       __lowerCAmelCase   (      A						):



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



						"""simple docstring"""






						_UpperCAmelCase			=       SMALL_MODEL_IDENTIFIER
						_UpperCAmelCase			=       'pt'
						_UpperCAmelCase			=       'tf'



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



						"""simple docstring"""






						_UpperCAmelCase			=       AutoModel.from_pretrained(self.test_model)
						model_pt.save_pretrained(A)



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



						"""simple docstring"""






						_UpperCAmelCase			=       TFAutoModel.from_pretrained(self.test_model			,		from_pt=A)
						model_tf.save_pretrained(A)



			def    _lowerCamelCase	(						self       :  Dict)       ->   List[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       'mock_framework'

						# Framework provided - return whatever the user provides
						_UpperCAmelCase			=       FeaturesManager.determine_framework(self.test_model			,		A)
						self.assertEqual(A			,		A)

						# Local checkpoint and framework provided - return provided framework
						# PyTorch checkpoint
						with TemporaryDirectory() as local_pt_ckpt:
									self._setup_pt_ckpt(A)
									_UpperCAmelCase			=       FeaturesManager.determine_framework(A			,		A)
									self.assertEqual(A			,		A)

						# TensorFlow checkpoint
						with TemporaryDirectory() as local_tf_ckpt:
									self._setup_tf_ckpt(A)
									_UpperCAmelCase			=       FeaturesManager.determine_framework(A			,		A)
									self.assertEqual(A			,		A)



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



						"""simple docstring"""






						with TemporaryDirectory() as local_pt_ckpt:
									self._setup_pt_ckpt(A)
									_UpperCAmelCase			=       FeaturesManager.determine_framework(A)
									self.assertEqual(A			,		self.framework_pt)

						# TensorFlow checkpoint
						with TemporaryDirectory() as local_tf_ckpt:
									self._setup_tf_ckpt(A)
									_UpperCAmelCase			=       FeaturesManager.determine_framework(A)
									self.assertEqual(A			,		self.framework_tf)

						# Invalid local checkpoint
						with TemporaryDirectory() as local_invalid_ckpt:
									with self.assertRaises(A):
												_UpperCAmelCase			=       FeaturesManager.determine_framework(A)



			def    _lowerCamelCase	(						self       :  Any)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       MagicMock(return_value=A)
						with patch('transformers.onnx.features.is_tf_available'			,		A):
									_UpperCAmelCase			=       FeaturesManager.determine_framework(self.test_model)
									self.assertEqual(A			,		self.framework_pt)

						# PyTorch not in environment -> use TensorFlow
						_UpperCAmelCase			=       MagicMock(return_value=A)
						with patch('transformers.onnx.features.is_torch_available'			,		A):
									_UpperCAmelCase			=       FeaturesManager.determine_framework(self.test_model)
									self.assertEqual(A			,		self.framework_tf)

						# Both in environment -> use PyTorch
						_UpperCAmelCase			=       MagicMock(return_value=A)
						_UpperCAmelCase			=       MagicMock(return_value=A)
						with patch('transformers.onnx.features.is_tf_available'			,		A), patch(
						    'transformers.onnx.features.is_torch_available'			,		A):
									_UpperCAmelCase			=       FeaturesManager.determine_framework(self.test_model)
									self.assertEqual(A			,		self.framework_pt)

						# Both not in environment -> raise error
						_UpperCAmelCase			=       MagicMock(return_value=A)
						_UpperCAmelCase			=       MagicMock(return_value=A)
						with patch('transformers.onnx.features.is_tf_available'			,		A), patch(
						    'transformers.onnx.features.is_torch_available'			,		A):
									with self.assertRaises(A):
												_UpperCAmelCase			=       FeaturesManager.determine_framework(self.test_model)





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