

import string

import numpy







def      A_ (       _UpperCAmelCase							,      _UpperCAmelCase       ):
						return b if a == 0 else greatest_common_divisor(b % a							,      _UpperCAmelCase       )



class     __lowercase							:




			"""simple docstring"""







			_UpperCAmelCase  :				str     				=	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  :				int     				=	numpy.vectorize(lambda UpperCAmelCase_      : x % 36      )

			_UpperCAmelCase  :				str     				=	numpy.vectorize(snake_case_      )



			def __init__(					self    :	List[str]  ,		lowerCAmelCase__    :	List[str]):
									SCREAMING_SNAKE_CASE_:					Optional[Any]    						=			self.modulus(UpperCamelCase__)  # mod36 calc's on the encrypt key
									self.check_determinant()  # validate the determinant of the encryption key
									SCREAMING_SNAKE_CASE_:					int    						=			encrypt_key.shape[0]



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Any  ,		lowerCAmelCase__    :	Tuple):
									return self.key_string.index(UpperCamelCase__)



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Optional[int]  ,		lowerCAmelCase__    :	Optional[Any]):
									return self.key_string[round(UpperCamelCase__)]



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Dict):
									SCREAMING_SNAKE_CASE_:					List[str]    						=			round(numpy.linalg.det(self.encrypt_key))

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

									SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			len(self.key_string)
									if greatest_common_divisor(UpperCamelCase__  ,		len(self.key_string)) != 1:
															SCREAMING_SNAKE_CASE_:					Optional[int]    						=			(
															    F"determinant modular {req_l} of encryption key({det}) "
															    F"is not co prime w.r.t {req_l}.\nTry another key."
															)
															raise ValueError(UpperCamelCase__)



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Optional[int]  ,		lowerCAmelCase__    :	Union[str, Any]):
									SCREAMING_SNAKE_CASE_:					Dict    						=			[char for char in text.upper() if char in self.key_string]

									SCREAMING_SNAKE_CASE_:					Dict    						=			chars[-1]
									while len(UpperCamelCase__) % self.break_key != 0:
															chars.append(UpperCamelCase__)

									return "".join(UpperCamelCase__)



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Optional[Any]  ,		lowerCAmelCase__    :	Optional[Any]):
									SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			self.process_text(text.upper())
									SCREAMING_SNAKE_CASE_:					Dict    						=			""

									for i in range(0  ,		len(UpperCamelCase__) - self.break_key + 1  ,		self.break_key):
															SCREAMING_SNAKE_CASE_:					Dict    						=			text[i : i + self.break_key]
															SCREAMING_SNAKE_CASE_:					Any    						=			[self.replace_letters(UpperCamelCase__) for char in batch]
															SCREAMING_SNAKE_CASE_:					str    						=			numpy.array([vec]).T
															SCREAMING_SNAKE_CASE_:					Optional[int]    						=			self.modulus(self.encrypt_key.dot(UpperCamelCase__)).T.tolist()[
															    0
															]
															SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			"".join(
															    self.replace_digits(UpperCamelCase__) for num in batch_encrypted)
															encrypted += encrypted_batch

									return encrypted



			def 			_SCREAMING_SNAKE_CASE     (					self    :	Tuple):
									SCREAMING_SNAKE_CASE_:					List[str]    						=			round(numpy.linalg.det(self.encrypt_key))

									if det < 0:
															SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			det % len(self.key_string)
									SCREAMING_SNAKE_CASE_:					Any    						=			None
									for i in range(len(self.key_string)):
															if (det * i) % len(self.key_string) == 1:
																					SCREAMING_SNAKE_CASE_:					Optional[Any]    						=			i
																					break

									SCREAMING_SNAKE_CASE_:					str    						=			(
									    det_inv
									    * numpy.linalg.det(self.encrypt_key)
									    * numpy.linalg.inv(self.encrypt_key)
									)

									return self.to_int(self.modulus(UpperCamelCase__))




			def 			_SCREAMING_SNAKE_CASE     (					self    :	Optional[Any]  ,		lowerCAmelCase__    :	Union[str, Any]):
									SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			self.make_decrypt_key()
									SCREAMING_SNAKE_CASE_:					str    						=			self.process_text(text.upper())
									SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			""

									for i in range(0  ,		len(UpperCamelCase__) - self.break_key + 1  ,		self.break_key):
															SCREAMING_SNAKE_CASE_:					int    						=			text[i : i + self.break_key]
															SCREAMING_SNAKE_CASE_:					Optional[int]    						=			[self.replace_letters(UpperCamelCase__) for char in batch]
															SCREAMING_SNAKE_CASE_:					Optional[Any]    						=			numpy.array([vec]).T
															SCREAMING_SNAKE_CASE_:					List[str]    						=			self.modulus(decrypt_key.dot(UpperCamelCase__)).T.tolist()[0]
															SCREAMING_SNAKE_CASE_:					int    						=			"".join(
															    self.replace_digits(UpperCamelCase__) for num in batch_decrypted)
															decrypted += decrypted_batch

									return decrypted







def      A_ (       ):
						SCREAMING_SNAKE_CASE_:					Dict    						=			int(input("Enter the order of the encryption key: "       )       )
						SCREAMING_SNAKE_CASE_:					Union[str, Any]    						=			[]

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

						SCREAMING_SNAKE_CASE_:					Tuple    						=			HillCipher(numpy.array(_UpperCAmelCase       )       )

						print("Would you like to encrypt or decrypt some text? (1 or 2)"       )
						SCREAMING_SNAKE_CASE_:					Any    						=			input("\n1. Encrypt\n2. Decrypt\n"       )
						if option == "1":
												SCREAMING_SNAKE_CASE_:					int    						=			input("What text would you like to encrypt?: "       )
												print("Your encrypted text is:"       )
												print(hc.encrypt(_UpperCAmelCase       )       )
						elif option == "2":
												SCREAMING_SNAKE_CASE_:					List[str]    						=			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()










"""simple docstring"""



import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
  import tensorflow as tf

if is_keras_nlp_available():
  from transformers.models.gpta import TFGPTaTokenizer


__snake_case       =       ["""gpt2"""]
__snake_case       =       """gpt2"""

if is_tf_available():







  class _lowerCAmelCase							( tf.Module      ):







     def __init__(      self		,      UpperCamelCase__		)      ->						Optional[Any]:

         '''simple docstring'''




         super().__init__()
         snake_case       : Dict    =       tokenizer
         snake_case       : List[str]    =       AutoConfig.from_pretrained(UpperCamelCase__		)
         snake_case       : List[str]    =       TFGPTaLMHeadModel.from_config(UpperCamelCase__		)







     @tf.function(input_signature=(tf.TensorSpec((None,)		,      tf.string		,      name="text"		),)		)
     def 					lowerCamelCase						(      self		,      UpperCamelCase__		)      ->						Optional[int]:

         '''simple docstring'''




         snake_case       : List[Any]    =       self.tokenizer(UpperCamelCase__		)
         snake_case       : Tuple    =       tokenized["input_ids"].to_tensor()

         snake_case       : str    =       tf.cast(input_ids_dense > 0		,      tf.intaa		)
         # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

         snake_case       : int    =       self.model(input_ids=UpperCamelCase__		,      attention_mask=UpperCamelCase__		)["logits"]

         return outputs







@require_tf
@require_keras_nlp
class _lowerCAmelCase							( unittest.TestCase      ):







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       super().setUp()

       snake_case       : Optional[int]    =       [GPTaTokenizer.from_pretrained(UpperCamelCase__		) for checkpoint in (TOKENIZER_CHECKPOINTS)]
       snake_case       : str    =       [TFGPTaTokenizer.from_pretrained(UpperCamelCase__		) for checkpoint in TOKENIZER_CHECKPOINTS]
       assert len(self.tokenizers		) == len(self.tf_tokenizers		)

       snake_case       : Optional[int]    =       [
           "This is a straightforward English test sentence.",
           "This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.",
           "Now we're going to add some Chinese: 一 二 三 一二三",
           "And some much more rare Chinese: 齉 堃 齉堃",
           "Je vais aussi écrire en français pour tester les accents",
           "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ",
       ]
       snake_case       : str    =       list(zip(self.test_sentences		,      self.test_sentences[::-1]		)		)







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

       '''simple docstring'''




       for tokenizer, tf_tokenizer in zip(self.tokenizers		,      self.tf_tokenizers		):
           for test_inputs in self.test_sentences:
               snake_case       : Any    =       tokenizer([test_inputs]		,      return_tensors="tf"		)
               snake_case       : str    =       tf_tokenizer([test_inputs]		)

               for key in python_outputs.keys():
                   # convert them to numpy to avoid messing with ragged tensors
                   snake_case       : Any    =       python_outputs[key].numpy()
                   snake_case       : Any    =       tf_outputs[key].numpy()

                   self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape		)		)
                   self.assertTrue(tf.reduce_all(tf.cast(UpperCamelCase__		,      tf.intaa		) == tf_outputs_values		)		)







   @slow
   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       for tf_tokenizer in self.tf_tokenizers:
           snake_case       : str    =       tf.function(UpperCamelCase__		)
           for test_inputs in self.test_sentences:
               snake_case       : str    =       tf.constant(UpperCamelCase__		)
               snake_case       : Optional[int]    =       compiled_tokenizer(UpperCamelCase__		)
               snake_case       : Dict    =       tf_tokenizer(UpperCamelCase__		)

               for key in eager_outputs.keys():
                   self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]		)		)







   @slow
   def 					lowerCamelCase						(      self		)      ->						Any:

       '''simple docstring'''




       for tf_tokenizer in self.tf_tokenizers:
           snake_case       : Tuple    =       ModelToSave(tokenizer=UpperCamelCase__		)
           snake_case       : Tuple    =       tf.convert_to_tensor([self.test_sentences[0]]		)
           snake_case       : Union[str, Any]    =       model.serving(UpperCamelCase__		)  # Build model with some sample inputs
           with TemporaryDirectory() as tempdir:
               snake_case       : int    =       Path(UpperCamelCase__		) / "saved.model"
               tf.saved_model.save(UpperCamelCase__		,      UpperCamelCase__		,      signatures={"serving_default": model.serving}		)
               snake_case       : Optional[Any]    =       tf.saved_model.load(UpperCamelCase__		)
           snake_case       : Union[str, Any]    =       loaded_model.signatures["serving_default"](UpperCamelCase__		)["output_0"]
           # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
           self.assertTrue(tf.reduce_all(out == loaded_output		)		)







   @slow
   def 					lowerCamelCase						(      self		)      ->						int:

       '''simple docstring'''




       for tf_tokenizer in self.tf_tokenizers:
           snake_case       : Any    =       tf.convert_to_tensor([self.test_sentences[0]]		)
           snake_case       : List[str]    =       tf_tokenizer(UpperCamelCase__		)  # Build model with some sample inputs

           snake_case       : Dict    =       tf_tokenizer.get_config()
           snake_case       : Union[str, Any]    =       TFGPTaTokenizer.from_config(UpperCamelCase__		)
           snake_case       : Optional[Any]    =       model_from_config(UpperCamelCase__		)

           for key in from_config_output.keys():
               self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]		)		)







   @slow
   def 					lowerCamelCase						(      self		)      ->						Tuple:

       '''simple docstring'''




       for tf_tokenizer in self.tf_tokenizers:
           # for the test to run
           snake_case       : List[str]    =       12_3123

           for max_length in [3, 5, 1024]:
               snake_case       : str    =       tf.convert_to_tensor([self.test_sentences[0]]		)
               snake_case       : List[Any]    =       tf_tokenizer(UpperCamelCase__		,      max_length=UpperCamelCase__		)

               snake_case       : str    =       out["input_ids"].numpy().shape[1]

               assert out_length == max_length





