



import os
import sys

from . import rsa_key_generator as rkg

A__       =			1_28
A__       =			2_56


def 						_UpperCAmelCase							( snake_case      ,		snake_case = DEFAULT_BLOCK_SIZE     ):





					"""simple docstring"""

					_lowerCAmelCase         =       message.encode("""ascii"""     )

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


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case = DEFAULT_BLOCK_SIZE     ):





					"""simple docstring"""

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


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case = DEFAULT_BLOCK_SIZE     ):





					"""simple docstring"""

					_lowerCAmelCase         =       []
					_lowerCAmelCase      ,      _lowerCAmelCase         =       key

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


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case      ,		snake_case = DEFAULT_BLOCK_SIZE      ,		):





					"""simple docstring"""

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


def 						_UpperCAmelCase							( snake_case     ):





					"""simple docstring"""

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


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case      ,		snake_case = DEFAULT_BLOCK_SIZE      ,		):





					"""simple docstring"""

					_lowerCAmelCase      ,      _lowerCAmelCase      ,      _lowerCAmelCase         =       read_key_file(snake_case     )
					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      ,		snake_case     )     )

					_lowerCAmelCase         =       [str(snake_case     ) for i in encrypt_message(snake_case      ,		(n, e)      ,		snake_case     )]

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


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

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

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

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

					return decrypt_message(snake_case      ,		snake_case      ,		(n, d)      ,		snake_case     )


def 						_UpperCAmelCase							( ):





					"""simple docstring"""

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

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

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

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

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

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

										print("""\nDecryption:"""     )
										print(snake_case     )


if __name__ == "__main__":
	main()











import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import SwinaSRImageProcessor
   from transformers.image_transforms import get_image_size


class 		lowerCAmelCase_				(  unittest.TestCase ):





     def __init__(	self							, _UpperCAmelCase							, _UpperCAmelCase=7							, _UpperCAmelCase=3							, _UpperCAmelCase=18							, _UpperCAmelCase=30							, _UpperCAmelCase=400							, _UpperCAmelCase=True							, _UpperCAmelCase=1 / 255							, _UpperCAmelCase=True							, _UpperCAmelCase=8							, )		->				Tuple:
        lowerCamelCase									=parent
        lowerCamelCase									=batch_size
        lowerCamelCase									=num_channels
        lowerCamelCase									=image_size
        lowerCamelCase									=min_resolution
        lowerCamelCase									=max_resolution
        lowerCamelCase									=do_rescale
        lowerCamelCase									=rescale_factor
        lowerCamelCase									=do_pad
        lowerCamelCase									=pad_size





     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        return {
            "do_rescale": self.do_rescale,
            "rescale_factor": self.rescale_factor,
            "do_pad": self.do_pad,
            "pad_size": self.pad_size,
        }





     def 						lowerCamelCase							(	self							, _UpperCAmelCase=False							, _UpperCAmelCase=False							, _UpperCAmelCase=False  )		->				int:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              image_inputs.append(
                  np.random.randint(
                      255							, size=(self.num_channels, self.max_resolution, self.max_resolution)							, dtype=np.uinta  )  )
        else:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              lowerCamelCase				,       lowerCamelCase									=np.random.choice(np.arange(self.min_resolution							, self.max_resolution  )							, 2  )
              image_inputs.append(np.random.randint(255							, size=(self.num_channels, width, height)							, dtype=np.uinta  )  )

        if not numpify and not torchify:
           # PIL expects the channel dimension as last dimension
           lowerCamelCase									=[Image.fromarray(np.moveaxis(_UpperCAmelCase							, 0							, -1  )  ) for x in image_inputs]

        if torchify:
           lowerCamelCase									=[torch.from_numpy(_UpperCAmelCase  ) for x in image_inputs]

        return image_inputs




@require_torch
@require_vision
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    Optional[Any] 	=     SwinaSRImageProcessor if is_vision_available() else None





     def 						lowerCamelCase							(	self  )		->				Dict:
        lowerCamelCase									=SwinaSRImageProcessingTester(self  )





     @property
     def 						lowerCamelCase							(	self  )		->				Any:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 						lowerCamelCase							(	self  )		->				Any:
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_rescale"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """rescale_factor"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_pad"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """pad_size"""  )  )





     def 						lowerCamelCase							(	self  )		->				Any:
        pass





     def 						lowerCamelCase							(	self							, _UpperCAmelCase  )		->				int:
        lowerCamelCase				,       lowerCamelCase									=get_image_size(_UpperCAmelCase  )
        lowerCamelCase									=self.image_processor_tester.pad_size

        lowerCamelCase									=(old_height // size + 1) * size - old_height
        lowerCamelCase									=(old_width // size + 1) * size - old_width
        return old_height + pad_height, old_width + pad_width





     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, Image.Image  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        lowerCamelCase				,       lowerCamelCase									=self.calculate_expected_size(np.array(image_inputs[0]  )  )
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )							, )





     def 						lowerCamelCase							(	self  )		->				Any:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random numpy tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, numpify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, np.ndarray  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        lowerCamelCase				,       lowerCamelCase									=self.calculate_expected_size(image_inputs[0]  )
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )							, )





     def 						lowerCamelCase							(	self  )		->				Dict:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PyTorch tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, torchify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, torch.Tensor  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        lowerCamelCase				,       lowerCamelCase									=self.calculate_expected_size(image_inputs[0]  )
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )							, )