



'''simple docstring'''


import os
import sys

from . import rsa_key_generator as rkg

lowercase											=      128
lowercase											=      256






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__ = DEFAULT_BLOCK_SIZE							):


     '''simple docstring'''







     a_									=message.encode("ascii"							)

     a_									=[]
     for block_start in range(0							,						len(lowercase__							)							,						lowercase__							):
          a_									=0
          for i in range(lowercase__							,						min(block_start + block_size							,						len(lowercase__							)							)							):
               block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
          block_ints.append(lowercase__							)
     return block_ints






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__							,						lowercase__ = DEFAULT_BLOCK_SIZE							):


     '''simple docstring'''







     a_									=[]
     for block_int in block_ints:
          a_									=[]
          for i in range(block_size - 1							,						-1							,						-1							):
               if len(lowercase__							) + i < message_length:
                    a_									=block_int // (BYTE_SIZE**i)
                    a_									=block_int % (BYTE_SIZE**i)
                    block_message.insert(0							,						chr(lowercase__							)							)
          message.extend(lowercase__							)
     return "".join(lowercase__							)






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__							,						lowercase__ = DEFAULT_BLOCK_SIZE							):


     '''simple docstring'''







     a_									=[]
     a_		,    a_									=key

     for block in get_blocks_from_text(lowercase__							,						lowercase__							):
          encrypted_blocks.append(pow(lowercase__							,						lowercase__							,						lowercase__							)							)
     return encrypted_blocks






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__							,						lowercase__							,						lowercase__ = DEFAULT_BLOCK_SIZE							,						):


     '''simple docstring'''







     a_									=[]
     a_		,    a_									=key
     for block in encrypted_blocks:
          decrypted_blocks.append(pow(lowercase__							,						lowercase__							,						lowercase__							)							)
     return get_text_from_blocks(lowercase__							,						lowercase__							,						lowercase__							)






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     with open(lowercase__							) as fo:
          a_									=fo.read()
     a_		,    a_		,    a_									=content.split(","							)
     return (int(lowercase__							), int(lowercase__							), int(lowercase__							))






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__							,						lowercase__							,						lowercase__ = DEFAULT_BLOCK_SIZE							,						):


     '''simple docstring'''







     a_		,    a_		,    a_									=read_key_file(lowercase__							)
     if key_size < block_size * 8:
          sys.exit(
              "ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
              "requires the block size to be equal to or greater than the key size. "
              "Either decrease the block size or use different keys.".format(
                  block_size * 8							,						lowercase__							)							)

     a_									=[str(lowercase__							) for i in encrypt_message(lowercase__							,						(n, e)							,						lowercase__							)]

     a_									=",".join(lowercase__							)
     a_									=F"""{len(lowercase__							)}_{block_size}_{encrypted_content}"""
     with open(lowercase__							,						"w"							) as fo:
          fo.write(lowercase__							)
     return encrypted_content






def 			UpperCAmelCase_							(		lowercase__							,						lowercase__							):


     '''simple docstring'''







     a_		,    a_		,    a_									=read_key_file(lowercase__							)
     with open(lowercase__							) as fo:
          a_									=fo.read()
     a_		,    a_		,    a_									=content.split("_"							)
     a_									=int(lowercase__							)
     a_									=int(lowercase__							)

     if key_size < block_size * 8:
          sys.exit(
              "ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
              "requires the block size to be equal to or greater than the key size. "
              "Did you specify the correct key file and encrypted file?".format(
                  block_size * 8							,						lowercase__							)							)

     a_									=[]
     for block in encrypted_message.split(","							):
          encrypted_blocks.append(int(lowercase__							)							)

     return decrypt_message(lowercase__							,						lowercase__							,						(n, d)							,						lowercase__							)






def 			UpperCAmelCase_							(		):


     '''simple docstring'''







     a_									="encrypted_file.txt"
     a_									=input(r"Encrypt\Decrypt [e\d]: "							)

     if response.lower().startswith("e"							):
          a_									="encrypt"
     elif response.lower().startswith("d"							):
          a_									="decrypt"

     if mode == "encrypt":
          if not os.path.exists("rsa_pubkey.txt"							):
               rkg.make_key_files("rsa"							,						1_0_2_4							)

          a_									=input("\nEnter message: "							)
          a_									="rsa_pubkey.txt"
          print(F"""Encrypting and writing to {filename}..."""							)
          a_									=encrypt_and_write_to_file(lowercase__							,						lowercase__							,						lowercase__							)

          print("\nEncrypted text:"							)
          print(lowercase__							)

     elif mode == "decrypt":
          a_									="rsa_privkey.txt"
          print(F"""Reading from {filename} and decrypting..."""							)
          a_									=read_from_file_and_decrypt(lowercase__							,						lowercase__							)
          print("writing decryption to rsa_decryption.txt..."							)
          with open("rsa_decryption.txt"							,						"w"							) as dec:
               dec.write(lowercase__							)

          print("\nDecryption:"							)
          print(lowercase__							)


if __name__ == "__main__":
  main()







'''simple docstring'''


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

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


lowercase											=      logging.get_logger(__name__)

lowercase											=      {
    '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/config.json''',
    '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/config.json''',
    '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/config.json''',
    '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/config.json''',
    '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/config.json''',
}







class 						UpperCAmelCase						(		__a):


 '''simple docstring'''




 __magic_name__       :			str	=   "gpt2"
 __magic_name__       :			str	=   ["past_key_values"]
 __magic_name__       :			Dict	=   {
     "hidden_size": "n_embd",
     "max_position_embeddings": "n_positions",
     "num_attention_heads": "n_head",
     "num_hidden_layers": "n_layer",
 }




 def __init__( self				,	lowerCAmelCase_=5_0_2_5_7				,	lowerCAmelCase_=1_0_2_4				,	lowerCAmelCase_=7_6_8				,	lowerCAmelCase_=1_2				,	lowerCAmelCase_=1_2				,	lowerCAmelCase_=None				,	lowerCAmelCase_="gelu_new"				,	lowerCAmelCase_=0.1				,	lowerCAmelCase_=0.1				,	lowerCAmelCase_=0.1				,	lowerCAmelCase_=1e-5				,	lowerCAmelCase_=0.0_2				,	lowerCAmelCase_="cls_index"				,	lowerCAmelCase_=True				,	lowerCAmelCase_=None				,	lowerCAmelCase_=True				,	lowerCAmelCase_=0.1				,	lowerCAmelCase_=True				,	lowerCAmelCase_=True				,	lowerCAmelCase_=5_0_2_5_6				,	lowerCAmelCase_=5_0_2_5_6				,	lowerCAmelCase_=False				,	lowerCAmelCase_=False				,	**lowerCAmelCase_				,	)			->   Dict:



      """simple docstring"""







      a_									=vocab_size
      a_									=n_positions
      a_									=n_embd
      a_									=n_layer
      a_									=n_head
      a_									=n_inner
      a_									=activation_function
      a_									=resid_pdrop
      a_									=embd_pdrop
      a_									=attn_pdrop
      a_									=layer_norm_epsilon
      a_									=initializer_range
      a_									=summary_type
      a_									=summary_use_proj
      a_									=summary_activation
      a_									=summary_first_dropout
      a_									=summary_proj_to_labels
      a_									=scale_attn_weights
      a_									=use_cache
      a_									=scale_attn_by_inverse_layer_idx
      a_									=reorder_and_upcast_attn

      a_									=bos_token_id
      a_									=eos_token_id

      super().__init__(bos_token_id=lowerCAmelCase_				,	eos_token_id=lowerCAmelCase_				,	**lowerCAmelCase_)







class 						UpperCAmelCase						(		__a):


 '''simple docstring'''




 def __init__( self				,	lowerCAmelCase_				,	lowerCAmelCase_ = "default"				,	lowerCAmelCase_ = None				,	lowerCAmelCase_ = False				,	)			->   List[str]:



      """simple docstring"""







      super().__init__(lowerCAmelCase_				,	task=lowerCAmelCase_				,	patching_specs=lowerCAmelCase_				,	use_past=lowerCAmelCase_)
      if not getattr(self._config				,	"pad_token_id"				,	lowerCAmelCase_):
           # TODO: how to do that better?
           a_									=0




 @property
 def    lowercase_	( self)			->   Mapping[str, Mapping[int, str]]:



      """simple docstring"""







      a_									=OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
      if self.use_past:
           self.fill_with_past_key_values_(lowerCAmelCase_				,	direction="inputs")
           a_									={0: "batch", 1: "past_sequence + sequence"}
      else:
           a_									={0: "batch", 1: "sequence"}

      return common_inputs




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      return self._config.n_layer




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      return self._config.n_head




 def    lowercase_	( self				,	lowerCAmelCase_				,	lowerCAmelCase_ = -1				,	lowerCAmelCase_ = -1				,	lowerCAmelCase_ = False				,	lowerCAmelCase_ = None				,	)			->   Mapping[str, Any]:



      """simple docstring"""







      a_									=super(lowerCAmelCase_				,	self).generate_dummy_inputs(
          lowerCAmelCase_				,	batch_size=lowerCAmelCase_				,	seq_length=lowerCAmelCase_				,	is_pair=lowerCAmelCase_				,	framework=lowerCAmelCase_)

      # We need to order the input in the way they appears in the forward()
      a_									=OrderedDict({"input_ids": common_inputs["input_ids"]})

      # Need to add the past_keys
      if self.use_past:
           if not is_torch_available():
                raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
           else:
                import torch

                a_		,    a_									=common_inputs["input_ids"].shape
                # Not using the same length for past_key_values
                a_									=seqlen + 2
                a_									=(
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                a_									=[
                    (torch.zeros(lowerCAmelCase_), torch.zeros(lowerCAmelCase_)) for _ in range(self.num_layers)
                ]

      a_									=common_inputs["attention_mask"]
      if self.use_past:
           a_									=ordered_inputs["attention_mask"].dtype
           a_									=torch.cat(
               [ordered_inputs["attention_mask"], torch.ones(lowerCAmelCase_				,	lowerCAmelCase_				,	dtype=lowerCAmelCase_)]				,	dim=1)

      return ordered_inputs




 @property
 def    lowercase_	( self)			->   int:



      """simple docstring"""







      return 1_3


