


import os
import sys

from . import rsa_key_generator as rkg

__lowerCamelCase   	=  128
__lowerCamelCase   	=  256



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase = DEFAULT_BLOCK_SIZE			):
     a_     :  Tuple				      =     message.encode("""ascii"""			)

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



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase = DEFAULT_BLOCK_SIZE			):
     a_     :  list[str]				      =     []
     for block_int in block_ints:
          a_     :  list[str]				      =     []
          for i in range(block_size - 1	,	-1	,	-1			):
               if len(__UpperCamelCase			) + i < message_length:
                    a_     :  List[Any]				      =     block_int // (BYTE_SIZE**i)
                    a_     :  Optional[Any]				      =     block_int % (BYTE_SIZE**i)
                    block_message.insert(0	,	chr(__UpperCamelCase			)			)
          message.extend(__UpperCamelCase			)
     return "".join(__UpperCamelCase			)



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase = DEFAULT_BLOCK_SIZE			):
     a_     :  str				      =     []
     a_      ,      a_     :  Tuple				      =     key

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



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase = DEFAULT_BLOCK_SIZE	,	):
     a_     :  Optional[int]				      =     []
     a_      ,      a_     :  Any				      =     key
     for block in encrypted_blocks:
          decrypted_blocks.append(pow(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase			)			)
     return get_text_from_blocks(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase			)



def 			_a      (    __UpperCamelCase			):
     with open(__UpperCamelCase			) as fo:
          a_     :  int				      =     fo.read()
     a_      ,      a_      ,      a_     :  Any				      =     content.split(""","""			)
     return (int(__UpperCamelCase			), int(__UpperCamelCase			), int(__UpperCamelCase			))



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase = DEFAULT_BLOCK_SIZE	,	):
     a_      ,      a_      ,      a_     :  List[Any]				      =     read_key_file(__UpperCamelCase			)
     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	,	__UpperCamelCase			)			)

     a_     :  int				      =     [str(__UpperCamelCase			) for i in encrypt_message(__UpperCamelCase	,	(n, e)	,	__UpperCamelCase			)]

     a_     :  Optional[Any]				      =     """,""".join(__UpperCamelCase			)
     a_     :  str				      =     F'''{len(__UpperCamelCase			)}_{block_size}_{encrypted_content}'''
     with open(__UpperCamelCase	,	"""w"""			) as fo:
          fo.write(__UpperCamelCase			)
     return encrypted_content



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase			):
     a_      ,      a_      ,      a_     :  str				      =     read_key_file(__UpperCamelCase			)
     with open(__UpperCamelCase			) as fo:
          a_     :  int				      =     fo.read()
     a_      ,      a_      ,      a_     :  Optional[int]				      =     content.split("""_"""			)
     a_     :  Any				      =     int(__UpperCamelCase			)
     a_     :  str				      =     int(__UpperCamelCase			)

     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	,	__UpperCamelCase			)			)

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

     return decrypt_message(__UpperCamelCase	,	__UpperCamelCase	,	(n, d)	,	__UpperCamelCase			)



def 			_a      (    ):
     a_     :  Any				      =     """encrypted_file.txt"""
     a_     :  Union[str, Any]				      =     input(r"""Encrypt\Decrypt [e\d]: """			)

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

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

          a_     :  Dict				      =     input("""\nEnter message: """			)
          a_     :  Optional[Any]				      =     """rsa_pubkey.txt"""
          print(F'''Encrypting and writing to {filename}...'''			)
          a_     :  Optional[Any]				      =     encrypt_and_write_to_file(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase			)

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

     elif mode == "decrypt":
          a_     :  Union[str, Any]				      =     """rsa_privkey.txt"""
          print(F'''Reading from {filename} and decrypting...'''			)
          a_     :  List[Any]				      =     read_from_file_and_decrypt(__UpperCamelCase	,	__UpperCamelCase			)
          print("""writing decryption to rsa_decryption.txt..."""			)
          with open("""rsa_decryption.txt"""	,	"""w"""			) as dec:
               dec.write(__UpperCamelCase			)

          print("""\nDecryption:"""			)
          print(__UpperCamelCase			)


if __name__ == "__main__":
       main()







import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
           SpeechaTextaDecoder,
           SpeechaTextaForCausalLM,
       )


@require_torch
class 	a__						:

       def __init__( self   :  Dict   ,				lowerCamelCase_   :  Any   ,				lowerCamelCase_   :  Dict=9_9   ,				lowerCamelCase_   :  List[Any]=1_3   ,				lowerCamelCase_   :  Dict=1_6   ,				lowerCamelCase_   :  Any=7   ,				lowerCamelCase_   :  Dict=True   ,				lowerCamelCase_   :  List[str]=True   ,				lowerCamelCase_   :  Tuple=True   ,				lowerCamelCase_   :  Any=False   ,				lowerCamelCase_   :  Union[str, Any]=True   ,				lowerCamelCase_   :  int=2   ,				lowerCamelCase_   :  Tuple=3_2   ,				lowerCamelCase_   :  int=4   ,				lowerCamelCase_   :  Dict=4   ,				lowerCamelCase_   :  str=3_0   ,				lowerCamelCase_   :  Optional[int]=0   ,				lowerCamelCase_   :  Optional[Any]=1   ,				lowerCamelCase_   :  Any=2   ,				lowerCamelCase_   :  Optional[int]=None   ,				):
            a_     :  Optional[Any]				      =     parent
            a_     :  Union[str, Any]				      =     batch_size
            a_     :  Tuple				      =     decoder_seq_length
            # For common tests
            a_     :  Union[str, Any]				      =     self.decoder_seq_length
            a_     :  List[str]				      =     is_training
            a_     :  int				      =     use_attention_mask
            a_     :  Dict				      =     use_labels

            a_     :  List[str]				      =     vocab_size
            a_     :  Optional[int]				      =     d_model
            a_     :  str				      =     d_model
            a_     :  Any				      =     decoder_layers
            a_     :  Tuple				      =     decoder_layers
            a_     :  Dict				      =     decoder_ffn_dim
            a_     :  List[str]				      =     decoder_attention_heads
            a_     :  List[Any]				      =     decoder_attention_heads
            a_     :  List[str]				      =     eos_token_id
            a_     :  Any				      =     bos_token_id
            a_     :  List[Any]				      =     pad_token_id
            a_     :  Dict				      =     decoder_start_token_id
            a_     :  Tuple				      =     use_cache
            a_     :  List[Any]				      =     max_position_embeddings

            a_     :  List[str]				      =     None
            a_     :  Any				      =     decoder_seq_length
            a_     :  List[Any]				      =     2
            a_     :  Optional[Any]				      =     1

       def     UpperCAmelCase( self   :  str     ):
            a_     :  Any				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  Any				      =     None
            if self.use_attention_mask:
                 a_     :  Optional[Any]				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				vocab_size=2     )

            a_     :  Tuple				      =     None
            if self.use_labels:
                 a_     :  int				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  int				      =     SpeechaTextaConfig(
                vocab_size=self.vocab_size   ,				d_model=self.d_model   ,				decoder_layers=self.decoder_layers   ,				decoder_ffn_dim=self.decoder_ffn_dim   ,				decoder_attention_heads=self.decoder_attention_heads   ,				eos_token_id=self.eos_token_id   ,				bos_token_id=self.bos_token_id   ,				use_cache=self.use_cache   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.decoder_start_token_id   ,				max_position_embeddings=self.max_position_embeddings   ,				)

            return (
                config,
                input_ids,
                attention_mask,
                lm_labels,
            )

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  List[str]   ,				):
            a_     :  List[Any]				      =     True
            a_     :  Optional[int]				      =     SpeechaTextaDecoder(config=lowerCamelCase_     ).to(lowerCamelCase_     ).eval()
            a_     :  Optional[int]				      =     input_ids[:2]

            input_ids[input_ids == 0] += 1
            # first forward pass
            a_     :  Union[str, Any]				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )
            a_     :  Tuple				      =     model(lowerCamelCase_     )
            a_     :  str				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )

            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     )     )
            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     ) + 1     )

            a_     :  Tuple				      =     outputs["""past_key_values"""]

            # create hypothetical next token and extent to next_input_ids
            a_     :  Any				      =     ids_tensor((2, 1)   ,				config.vocab_size - 1     ) + 1

            # append to next input_ids and
            a_     :  str				      =     torch.cat([input_ids, next_tokens]   ,				dim=-1     )

            print(lowerCamelCase_     )

            a_     :  Any				      =     model(lowerCamelCase_     )["""last_hidden_state"""]
            a_     :  int				      =     model(lowerCamelCase_   ,				past_key_values=lowerCamelCase_     )["""last_hidden_state"""]

            # select random slice
            a_     :  Tuple				      =     ids_tensor((1,)   ,				output_from_past.shape[-1]     ).item()
            a_     :  List[str]				      =     output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
            a_     :  List[Any]				      =     output_from_past[:, 0, random_slice_idx].detach()

            # test that outputs are equal for slice
            assert torch.allclose(lowerCamelCase_   ,				lowerCamelCase_   ,				atol=1E-3     )

       def     UpperCAmelCase( self   :  Any     ):
            a_     :  List[Any]				      =     self.prepare_config_and_inputs()
            (
                (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      
            )     :  Optional[int]				      =     config_and_inputs

            a_     :  Tuple				      =     {
                """input_ids""": input_ids,
                """attention_mask""": attention_mask,
            }
            return config, inputs_dict


@require_torch
class 	a__						(    lowerCAmelCase_    ,							lowerCAmelCase_    ,							lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  int				     =  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  {"""text-generation""": SpeechaTextaForCausalLM} if is_torch_available() else {}
       lowerCamelCase__:  Dict				     =  True
       lowerCamelCase__:  List[Any]				     =  False

       def     UpperCAmelCase( self   :  List[str]   ,				):
            a_     :  Optional[int]				      =     SpeechaTextaStandaloneDecoderModelTester(self   ,				is_training=lowerCamelCase_     )
            a_     :  str				      =     ConfigTester(self   ,				config_class=lowerCamelCase_     )

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  str     ):
            self.config_tester.run_common_tests()

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  int				      =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase_     )

       def     UpperCAmelCase( self   :  int     ):
            return



