






'''simple docstring'''







import string

import numpy





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	int:
       return b if a == 0 else greatest_common_divisor(b % a    ,      _snake_case				)

class _lowercase     :
       a    				=	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)
       a    				=	numpy.vectorize(lambda _lowercase		: x % 36		)

       a    				=	numpy.vectorize(_lowercase		)




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




       def 		lowerCamelCase_    (							self:    Dict      ,							UpperCamelCase__:    Tuple					):
              return self.key_string.index(_a					)




       def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    Any					):
              return self.key_string[round(_a					)]




       def 		lowerCamelCase_    (							self:    Tuple					):
              lowerCamelCase__ :     Dict	  =	round(numpy.linalg.det(self.encrypt_key					)					)

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

              lowerCamelCase__ :     List[str]	  =	len(self.key_string					)
              if greatest_common_divisor(_a      ,							len(self.key_string					)					) != 1:
                     lowerCamelCase__ :     List[str]	  =	(
                         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:    Optional[int]      ,							UpperCamelCase__:    Union[str, Any]					):
              lowerCamelCase__ :     Dict	  =	[char for char in text.upper() if char in self.key_string]

              lowerCamelCase__ :     List[Any]	  =	chars[-1]
              while len(_a					) % self.break_key != 0:
                     chars.append(_a					)

              return "".join(_a					)




       def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    int					):
              lowerCamelCase__ :     Tuple	  =	self.process_text(text.upper()					)
              lowerCamelCase__ :     Union[str, Any]	  =	""

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

              return encrypted




       def 		lowerCamelCase_    (							self:    Tuple					):
              lowerCamelCase__ :     Union[str, Any]	  =	round(numpy.linalg.det(self.encrypt_key					)					)

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

              lowerCamelCase__ :     Union[str, Any]	  =	(
                  det_inv
                  * numpy.linalg.det(self.encrypt_key					)
                  * numpy.linalg.inv(self.encrypt_key					)
              )

              return self.to_int(self.modulus(_a					)					)




       def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    Union[str, Any]					):
              lowerCamelCase__ :     Tuple	  =	self.make_decrypt_key()
              lowerCamelCase__ :     Dict	  =	self.process_text(text.upper()					)
              lowerCamelCase__ :     Any	  =	""

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

              return decrypted





def 			SCREAMING_SNAKE_CASE_	()				->	None:
       lowerCamelCase__ :     Union[str, Any]	  =	int(input("""Enter the order of the encryption key: """				)				)
       lowerCamelCase__ :     str	  =	[]

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

       lowerCamelCase__ :     Any	  =	HillCipher(numpy.array(_snake_case				)				)

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


if __name__ == "__main__":
   import doctest

   doctest.testmod()

   main()









'''simple docstring'''







from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_A     :      Optional[Any]   					=logging.get_logger(__name__)

_A     :      List[str]   					={
    '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''',
    # See all Marian models at https://huggingface.co/models?filter=marian
}

class _lowercase     (    _lowercase		):
							a    				=	"""marian"""
							a    				=	["""past_key_values"""]
							a    				=	{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




							def __init__(							self:    Tuple      ,							UpperCamelCase__:    Optional[Any]=58_101      ,							UpperCamelCase__:    Optional[int]=None      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Any=12      ,							UpperCamelCase__:    Optional[int]=4_096      ,							UpperCamelCase__:    Tuple=16      ,							UpperCamelCase__:    Dict=12      ,							UpperCamelCase__:    Optional[Any]=4_096      ,							UpperCamelCase__:    Any=16      ,							UpperCamelCase__:    List[str]=0.0      ,							UpperCamelCase__:    Tuple=0.0      ,							UpperCamelCase__:    str=True      ,							UpperCamelCase__:    Optional[int]=True      ,							UpperCamelCase__:    Optional[int]="gelu"      ,							UpperCamelCase__:    Union[str, Any]=1_024      ,							UpperCamelCase__:    Optional[int]=0.1      ,							UpperCamelCase__:    Optional[Any]=0.0      ,							UpperCamelCase__:    Optional[Any]=0.0      ,							UpperCamelCase__:    Optional[int]=0.02      ,							UpperCamelCase__:    str=58_100      ,							UpperCamelCase__:    Tuple=False      ,							UpperCamelCase__:    Optional[Any]=58_100      ,							UpperCamelCase__:    int=0      ,							UpperCamelCase__:    Union[str, Any]=0      ,							UpperCamelCase__:    List[str]=True      ,							**UpperCamelCase__:    str      ,							):
														lowerCamelCase__ :     int	  =	vocab_size
														lowerCamelCase__ :     Tuple	  =	decoder_vocab_size or vocab_size
														lowerCamelCase__ :     List[str]	  =	max_position_embeddings
														lowerCamelCase__ :     Optional[Any]	  =	d_model
														lowerCamelCase__ :     int	  =	encoder_ffn_dim
														lowerCamelCase__ :     Union[str, Any]	  =	encoder_layers
														lowerCamelCase__ :     Dict	  =	encoder_attention_heads
														lowerCamelCase__ :     Optional[int]	  =	decoder_ffn_dim
														lowerCamelCase__ :     List[str]	  =	decoder_layers
														lowerCamelCase__ :     Dict	  =	decoder_attention_heads
														lowerCamelCase__ :     int	  =	dropout
														lowerCamelCase__ :     str	  =	attention_dropout
														lowerCamelCase__ :     Dict	  =	activation_dropout
														lowerCamelCase__ :     List[str]	  =	activation_function
														lowerCamelCase__ :     Union[str, Any]	  =	init_std
														lowerCamelCase__ :     str	  =	encoder_layerdrop
														lowerCamelCase__ :     Any	  =	decoder_layerdrop
														lowerCamelCase__ :     List[str]	  =	use_cache
														lowerCamelCase__ :     List[str]	  =	encoder_layers
														lowerCamelCase__ :     int	  =	scale_embedding  # scale factor will be sqrt(d_model) if True
														lowerCamelCase__ :     str	  =	share_encoder_decoder_embeddings
														super().__init__(
														    pad_token_id=UpperCamelCase__      ,							eos_token_id=UpperCamelCase__      ,							is_encoder_decoder=UpperCamelCase__      ,							decoder_start_token_id=UpperCamelCase__      ,							forced_eos_token_id=UpperCamelCase__      ,							**UpperCamelCase__      ,							)



class _lowercase     (    _lowercase		):




							@property
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     List[str]	  =	OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]					)

																					if self.use_past:
																												lowerCamelCase__ :     Dict	  =	{0: """batch"""}
																												lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 1: """past_decoder_sequence + sequence"""}
																					else:
																												lowerCamelCase__ :     Any	  =	{0: """batch""", 1: """decoder_sequence"""}
																												lowerCamelCase__ :     Dict	  =	{0: """batch""", 1: """decoder_sequence"""}

																					if self.use_past:
																												self.fill_with_past_key_values_(UpperCamelCase__      ,							direction="""inputs"""					)
														elif self.task == "causal-lm":
																					# TODO: figure this case out.
																					lowerCamelCase__ :     Union[str, Any]	  =	OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]					)
																					if self.use_past:
																												lowerCamelCase__  ,		lowerCamelCase__ :     Tuple	  =	self.num_layers
																												for i in range(UpperCamelCase__					):
																																			lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
																																			lowerCamelCase__ :     List[str]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
														else:
																					lowerCamelCase__ :     int	  =	OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
																					        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
																					    ]					)

														return common_inputs




							@property
							# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	super().outputs
														else:
																					lowerCamelCase__ :     Any	  =	super(UpperCamelCase__      ,							self					).outputs
																					if self.use_past:
																												lowerCamelCase__  ,		lowerCamelCase__ :     str	  =	self.num_layers
																												for i in range(UpperCamelCase__					):
																																			lowerCamelCase__ :     Tuple	  =	{0: """batch""", 2: """past_sequence + sequence"""}
																																			lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 2: """past_sequence + sequence"""}
														return common_outputs




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														lowerCamelCase__ :     Union[str, Any]	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)

														# Generate decoder inputs
														lowerCamelCase__ :     Any	  =	seq_length if not self.use_past else 1
														lowerCamelCase__ :     Optional[Any]	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
														lowerCamelCase__ :     str	  =	{F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
														lowerCamelCase__ :     Optional[int]	  =	dict(**UpperCamelCase__      ,							**UpperCamelCase__					)

														if self.use_past:
																					if not is_torch_available():
																												raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""					)
																					else:
																												import torch
																					lowerCamelCase__  ,		lowerCamelCase__ :     Optional[Any]	  =	common_inputs["""input_ids"""].shape
																					lowerCamelCase__ :     Tuple	  =	common_inputs["""decoder_input_ids"""].shape[1]
																					lowerCamelCase__  ,		lowerCamelCase__ :     List[str]	  =	self.num_attention_heads
																					lowerCamelCase__ :     Any	  =	(
																					    batch,
																					    num_encoder_attention_heads,
																					    encoder_seq_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)
																					lowerCamelCase__ :     Tuple	  =	decoder_seq_length + 3
																					lowerCamelCase__ :     int	  =	(
																					    batch,
																					    num_decoder_attention_heads,
																					    decoder_past_length,
																					    self._config.hidden_size // num_decoder_attention_heads,
																					)

																					lowerCamelCase__ :     Optional[int]	  =	torch.cat(
																					    [common_inputs["""decoder_attention_mask"""], torch.ones(UpperCamelCase__      ,							UpperCamelCase__					)]      ,							dim=1					)

																					lowerCamelCase__ :     Any	  =	[]
																					# If the number of encoder and decoder layers are present in the model configuration, both are considered
																					lowerCamelCase__  ,		lowerCamelCase__ :     Any	  =	self.num_layers
																					lowerCamelCase__ :     str	  =	min(UpperCamelCase__      ,							UpperCamelCase__					)
																					lowerCamelCase__ :     str	  =	max(UpperCamelCase__      ,							UpperCamelCase__					) - min_num_layers
																					lowerCamelCase__ :     int	  =	"""encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

																					for _ in range(UpperCamelCase__					):
																												common_inputs["past_key_values"].append(
																												    (
																												        torch.zeros(UpperCamelCase__					),
																												        torch.zeros(UpperCamelCase__					),
																												        torch.zeros(UpperCamelCase__					),
																												        torch.zeros(UpperCamelCase__					),
																												    )					)
																					# TODO: test this.
																					lowerCamelCase__ :     Union[str, Any]	  =	encoder_shape if remaining_side_name == """encoder""" else decoder_shape
																					for _ in range(UpperCamelCase__      ,							UpperCamelCase__					):
																												common_inputs["past_key_values"].append((torch.zeros(UpperCamelCase__					), torch.zeros(UpperCamelCase__					))					)
														return common_inputs




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														lowerCamelCase__ :     Any	  =	self._generate_dummy_inputs_for_encoder_and_decoder(
														    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)

														if self.use_past:
																					if not is_torch_available():
																												raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""					)
																					else:
																												import torch
																					lowerCamelCase__  ,		lowerCamelCase__ :     Any	  =	common_inputs["""input_ids"""].shape
																					# Not using the same length for past_key_values
																					lowerCamelCase__ :     Optional[Any]	  =	seqlen + 2
																					lowerCamelCase__  ,		lowerCamelCase__ :     Dict	  =	self.num_layers
																					lowerCamelCase__  ,		lowerCamelCase__ :     Dict	  =	self.num_attention_heads
																					lowerCamelCase__ :     Optional[Any]	  =	(
																					    batch,
																					    num_encoder_attention_heads,
																					    past_key_values_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)

																					lowerCamelCase__ :     Optional[Any]	  =	common_inputs["""attention_mask"""].dtype
																					lowerCamelCase__ :     int	  =	torch.cat(
																					    [common_inputs["""attention_mask"""], torch.ones(UpperCamelCase__      ,							UpperCamelCase__      ,							dtype=UpperCamelCase__					)]      ,							dim=1					)
																					lowerCamelCase__ :     int	  =	[
																					    (torch.zeros(UpperCamelCase__					), torch.zeros(UpperCamelCase__					)) for _ in range(UpperCamelCase__					)
																					]
														return common_inputs




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														# Copied from OnnxConfig.generate_dummy_inputs
														# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
														# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
														lowerCamelCase__ :     List[Any]	  =	compute_effective_axis_dimension(
														    UpperCamelCase__      ,							fixed_dimension=OnnxConfig.default_fixed_batch      ,							num_token_to_add=0					)

														# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
														lowerCamelCase__ :     Union[str, Any]	  =	tokenizer.num_special_tokens_to_add(UpperCamelCase__					)
														lowerCamelCase__ :     Any	  =	compute_effective_axis_dimension(
														    UpperCamelCase__      ,							fixed_dimension=OnnxConfig.default_fixed_sequence      ,							num_token_to_add=UpperCamelCase__					)

														# Generate dummy inputs according to compute batch and sequence
														lowerCamelCase__ :     Union[str, Any]	  =	[""" """.join([tokenizer.unk_token]					) * seq_length] * batch_size
														lowerCamelCase__ :     str	  =	dict(tokenizer(UpperCamelCase__      ,							return_tensors=UpperCamelCase__					)					)
														return common_inputs




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    PreTrainedTokenizer      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    int = -1      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    Optional[TensorType] = None      ,							):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																					    UpperCamelCase__      ,							batch_size=UpperCamelCase__      ,							seq_length=UpperCamelCase__      ,							is_pair=UpperCamelCase__      ,							framework=UpperCamelCase__					)

														else:
																					lowerCamelCase__ :     Tuple	  =	self._generate_dummy_inputs_for_causal_lm(
																					    UpperCamelCase__      ,							batch_size=UpperCamelCase__      ,							seq_length=UpperCamelCase__      ,							is_pair=UpperCamelCase__      ,							framework=UpperCamelCase__					)

														return common_inputs




							def 		lowerCamelCase_    (							self:    Union[str, Any]      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    List[Any]      ,							UpperCamelCase__:    Dict      ,							UpperCamelCase__:    Optional[Any]					):
														if self.task in ["default", "seq2seq-lm"]:
																					lowerCamelCase__ :     Dict	  =	super()._flatten_past_key_values_(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
														else:
																					lowerCamelCase__ :     List[Any]	  =	super(UpperCamelCase__      ,							self					)._flatten_past_key_values_(
																					    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)




							@property
							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														return 1e-4

