




import string

import numpy

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






class  __magic_name__						:
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							Tuple	      =					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)
				SCREAMING_SNAKE_CASE__					:							Dict	      =					numpy.vectorize(lambda __UpperCAmelCase: x % 36)

				SCREAMING_SNAKE_CASE__					:							Optional[int]	      =					numpy.vectorize(__UpperCAmelCase)


				def __init__(							self:   Tuple		,					_lowerCamelCase:   numpy.ndarray		):
											SCREAMING_SNAKE_CASE_   	=    self.modulus(_lowerCamelCase		)  # mod36 calc's on the encrypt key
											self.check_determinant()  # validate the determinant of the encryption key
											SCREAMING_SNAKE_CASE_   	=    encrypt_key.shape[0]


				def     _A							(							self:   Optional[Any]		,					_lowerCamelCase:   str		):
											return self.key_string.index(_lowerCamelCase		)


				def     _A							(							self:   List[str]		,					_lowerCamelCase:   int		):
											return self.key_string[round(_lowerCamelCase		)]


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

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

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


				def     _A							(							self:   Dict		,					_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    [char for char in text.upper() if char in self.key_string]

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

											return "".join(_lowerCamelCase		)


				def     _A							(							self:   Optional[int]		,					_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    self.process_text(text.upper()		)
											SCREAMING_SNAKE_CASE_   	=    ''''''

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

											return encrypted


				def     _A							(							self:   str		):
											SCREAMING_SNAKE_CASE_   	=    round(numpy.linalg.det(self.encrypt_key		)		)

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

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

											return self.to_int(self.modulus(_lowerCamelCase		)		)





				def     _A							(							self:   Union[str, Any]		,					_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    self.make_decrypt_key()
											SCREAMING_SNAKE_CASE_   	=    self.process_text(text.upper()		)
											SCREAMING_SNAKE_CASE_   	=    ''''''

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

											return decrypted






def 			a   ():
							SCREAMING_SNAKE_CASE_   	=    int(input('''Enter the order of the encryption key: '''     )     )
							SCREAMING_SNAKE_CASE_   	=    []

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

							SCREAMING_SNAKE_CASE_   	=    HillCipher(numpy.array(_lowerCAmelCase     )     )

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


if __name__ == "__main__":
			import doctest

			doctest.testmod()

			main()











import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__SCREAMING_SNAKE_CASE 						=logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE 						="""▁"""

__SCREAMING_SNAKE_CASE 						={"""vocab_file""": """spiece.model"""}

__SCREAMING_SNAKE_CASE 						={
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    }
}

__SCREAMING_SNAKE_CASE 						={
    """google/reformer-crime-and-punishment""": 524_288,
}






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							Any	      =					VOCAB_FILES_NAMES
				SCREAMING_SNAKE_CASE__					:							Union[str, Any]	      =					PRETRAINED_VOCAB_FILES_MAP
				SCREAMING_SNAKE_CASE__					:							Optional[int]	      =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				SCREAMING_SNAKE_CASE__					:							Union[str, Any]	      =					["input_ids", "attention_mask"]


				def __init__(							self:   List[Any]		,					_lowerCamelCase:   List[Any]		,					_lowerCamelCase:   List[Any]="</s>"		,					_lowerCamelCase:   str="<unk>"		,					_lowerCamelCase:   Union[str, Any]=[]		,					_lowerCamelCase:   Optional[Dict[str, Any]] = None		,					**_lowerCamelCase:   List[str]		,					):
											SCREAMING_SNAKE_CASE_   	=    {} if sp_model_kwargs is None else sp_model_kwargs

											super().__init__(
											    eos_token=_lowerCamelCase		,					unk_token=_lowerCamelCase		,					additional_special_tokens=_lowerCamelCase		,					sp_model_kwargs=self.sp_model_kwargs		,					**_lowerCamelCase		,					)

											SCREAMING_SNAKE_CASE_   	=    vocab_file
											SCREAMING_SNAKE_CASE_   	=    spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.Load(_lowerCamelCase		)


				@property
				def     _A							(							self:   Optional[int]		):
											return self.sp_model.get_piece_size()


				def     _A							(							self:   int		):
											SCREAMING_SNAKE_CASE_   	=    {self.convert_ids_to_tokens(_lowerCamelCase		): i for i in range(self.vocab_size		)}
											vocab.update(self.added_tokens_encoder		)
											return vocab


				def __getstate__(							self:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    self.__dict__.copy()
											SCREAMING_SNAKE_CASE_   	=    None
											return state


				def __setstate__(							self:   Dict		,					_lowerCamelCase:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_   	=    d

											# for backward compatibility
											if not hasattr(self		,					'''sp_model_kwargs'''		):
																		SCREAMING_SNAKE_CASE_   	=    {}

											SCREAMING_SNAKE_CASE_   	=    spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.Load(self.vocab_file		)


				def     _A							(							self:   Optional[Any]		,					_lowerCamelCase:   str		):
											return self.sp_model.encode(_lowerCamelCase		,					out_type=_lowerCamelCase		)


				def     _A							(							self:   int		,					_lowerCamelCase:   Optional[int]		):
											return self.sp_model.piece_to_id(_lowerCamelCase		)


				def     _A							(							self:   Union[str, Any]		,					_lowerCamelCase:   Tuple		):
											if index < self.sp_model.get_piece_size():
																		SCREAMING_SNAKE_CASE_   	=    self.sp_model.IdToPiece(_lowerCamelCase		)
											return token


				def     _A							(							self:   List[str]		,					_lowerCamelCase:   int		):
											SCREAMING_SNAKE_CASE_   	=    []
											SCREAMING_SNAKE_CASE_   	=    ''''''
											for token in tokens:
																		# make sure that special tokens are not decoded using sentencepiece model
																		if token in self.all_special_tokens:
																									out_string += self.sp_model.decode(_lowerCamelCase		) + token
																									SCREAMING_SNAKE_CASE_   	=    []
																		else:
																									current_sub_tokens.append(_lowerCamelCase		)
											out_string += self.sp_model.decode(_lowerCamelCase		)
											return out_string.strip()





				def     _A							(							self:   Optional[int]		,					_lowerCamelCase:   str		,					_lowerCamelCase:   Optional[str] = None		):
											if not os.path.isdir(_lowerCamelCase		):
																		logger.error(f"Vocabulary path ({save_directory}) should be a directory"		)
																		return
											SCREAMING_SNAKE_CASE_   	=    os.path.join(
											    _lowerCamelCase		,					(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']		)

											if os.path.abspath(self.vocab_file		) != os.path.abspath(_lowerCamelCase		) and os.path.isfile(self.vocab_file		):
																		copyfile(self.vocab_file		,					_lowerCamelCase		)
											elif not os.path.isfile(self.vocab_file		):
																		with open(_lowerCamelCase		,					'''wb'''		) as fi:
																									SCREAMING_SNAKE_CASE_   	=    self.sp_model.serialized_model_proto()
																									fi.write(_lowerCamelCase		)

											return (out_vocab_file,)


