


"""simple docstring"""




import os
import sys

from . import rsa_key_generator as rkg

lowerCAmelCase__						=			1_28
lowerCAmelCase__						=			2_56
def 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  int = DEFAULT_BLOCK_SIZE						):
       _A				:	Dict       =			message.encode("ascii"						)

       _A				:	str       =			[]
       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 							_UpperCAmelCase    (UpperCamelCase__					:  list[int]    ,							UpperCamelCase__					:  int    ,							UpperCamelCase__					:  int = 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				:	Dict       =			block_int % (BYTE_SIZE**i)
                            block_message.insert(0    ,							chr(UpperCamelCase__						)						)
              message.extend(UpperCamelCase__						)
       return "".join(UpperCamelCase__						)
def 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  tuple[int, int]    ,							UpperCamelCase__					:  int = DEFAULT_BLOCK_SIZE						):
       _A				:	str       =			[]
       _A				:	str       =			key

       for block in get_blocks_from_text(UpperCamelCase__    ,							UpperCamelCase__						):
              encrypted_blocks.append(pow(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__						)						)
       return encrypted_blocks
def 							_UpperCAmelCase    (UpperCamelCase__					:  list[int]    ,							UpperCamelCase__					:  int    ,							UpperCamelCase__					:  tuple[int, int]    ,							UpperCamelCase__					:  int = DEFAULT_BLOCK_SIZE    ,							):
       _A				:	List[str]       =			[]
       _A				:	Dict       =			key
       for block in encrypted_blocks:
              decrypted_blocks.append(pow(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__						)						)
       return get_text_from_blocks(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__						)
def 							_UpperCAmelCase    (UpperCamelCase__					:  str						):
       with open(UpperCamelCase__						) as fo:
              _A				:	List[Any]       =			fo.read()
       _A				:	Any       =			content.split(","						)
       return (int(UpperCamelCase__						), int(UpperCamelCase__						), int(UpperCamelCase__						))
def 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  str    ,							UpperCamelCase__					:  str    ,							UpperCamelCase__					:  int = DEFAULT_BLOCK_SIZE    ,							):
       _A				:	str       =			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				:	Tuple       =			[str(UpperCamelCase__						) for i in encrypt_message(UpperCamelCase__    ,							(n, e)    ,							UpperCamelCase__						)]

       _A				:	Any       =			",".join(UpperCamelCase__						)
       _A				:	Any       =			f"{len(UpperCamelCase__						)}_{block_size}_{encrypted_content}"
       with open(UpperCamelCase__    ,							"w"						) as fo:
              fo.write(UpperCamelCase__						)
       return encrypted_content
def 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  str						):
       _A				:	Tuple       =			read_key_file(UpperCamelCase__						)
       with open(UpperCamelCase__						) as fo:
              _A				:	Tuple       =			fo.read()
       _A				:	Dict       =			content.split("_"						)
       _A				:	Any       =			int(UpperCamelCase__						)
       _A				:	int       =			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				:	Dict       =			[]
       for block in encrypted_message.split(","						):
              encrypted_blocks.append(int(UpperCamelCase__						)						)

       return decrypt_message(UpperCamelCase__    ,							UpperCamelCase__    ,							(n, d)    ,							UpperCamelCase__						)
def 							_UpperCAmelCase    ():
       _A				:	Optional[int]       =			"encrypted_file.txt"
       _A				:	List[Any]       =			input(r"Encrypt\Decrypt [e\d]: "						)

       if response.lower().startswith("e"						):
              _A				:	Dict       =			"encrypt"
       elif response.lower().startswith("d"						):
              _A				:	List[str]       =			"decrypt"

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

              _A				:	Optional[int]       =			input("\nEnter message: "						)
              _A				:	List[Any]       =			"rsa_pubkey.txt"
              print(f"Encrypting and writing to {filename}..."						)
              _A				:	List[Any]       =			encrypt_and_write_to_file(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__						)

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

       elif mode == "decrypt":
              _A				:	Dict       =			"rsa_privkey.txt"
              print(f"Reading from {filename} and decrypting..."						)
              _A				:	List[str]       =			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

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):




     '''simple docstring'''


     def __init__(						self			,						__lowerCamelCase			,						__lowerCamelCase=7			,						__lowerCamelCase=3			,						__lowerCamelCase=1_8			,						__lowerCamelCase=3_0			,						__lowerCamelCase=4_0_0			,						__lowerCamelCase=True			,						__lowerCamelCase=1 / 2_5_5			,						__lowerCamelCase=True			,						__lowerCamelCase=8			,						)      ->    Optional[Any]:
            _A				:	List[str]       =			parent
            _A				:	str       =			batch_size
            _A				:	Any       =			num_channels
            _A				:	Any       =			image_size
            _A				:	Optional[int]       =			min_resolution
            _A				:	Union[str, Any]       =			max_resolution
            _A				:	Optional[Any]       =			do_rescale
            _A				:	str       =			rescale_factor
            _A				:	str       =			do_pad
            _A				:	Dict       =			pad_size


     def 			_lowerCamelCase			(						self)      ->    str:
            return {
                "do_rescale": self.do_rescale,
                "rescale_factor": self.rescale_factor,
                "do_pad": self.do_pad,
                "pad_size": self.pad_size,
            }


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

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

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

            if torchify:
                   _A				:	Union[str, Any]       =			[torch.from_numpy(__lowerCamelCase) for x in image_inputs]

            return image_inputs







@require_torch
@require_vision
class 					lowerCAmelCase__	(    a					,   unittest.TestCase):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			SwinaSRImageProcessor if is_vision_available() else None


     def 			_lowerCamelCase			(						self)      ->    Any:
            _A				:	int       =			SwinaSRImageProcessingTester(self)


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


     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            _A				:	Tuple       =			self.image_processing_class(**self.image_processor_dict)
            self.assertTrue(hasattr(__lowerCamelCase			,						"do_rescale"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"rescale_factor"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"do_pad"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"pad_size"))


     def 			_lowerCamelCase			(						self)      ->    Dict:
            pass


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase)      ->    Tuple:
            _A   ,      _A				:	Dict       =			get_image_size(__lowerCamelCase)
            _A				:	Tuple       =			self.image_processor_tester.pad_size

            _A				:	Dict       =			(old_height // size + 1) * size - old_height
            _A				:	Any       =			(old_width // size + 1) * size - old_width
            return old_height + pad_height, old_width + pad_width


     def 			_lowerCamelCase			(						self)      ->    Dict:
            # Initialize image_processor
            _A				:	Optional[int]       =			self.image_processing_class(**self.image_processor_dict)
            # create random PIL images
            _A				:	Union[str, Any]       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						Image.Image)

            # Test not batched input
            _A				:	str       =			image_processor(image_inputs[0]			,						return_tensors="pt").pixel_values
            _A   ,      _A				:	int       =			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)      ->    int:
            # Initialize image_processor
            _A				:	Any       =			self.image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            _A				:	int       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase			,						numpify=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						np.ndarray)

            # Test not batched input
            _A				:	Union[str, Any]       =			image_processor(image_inputs[0]			,						return_tensors="pt").pixel_values
            _A   ,      _A				:	Union[str, Any]       =			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)      ->    Optional[Any]:
            # Initialize image_processor
            _A				:	str       =			self.image_processing_class(**self.image_processor_dict)
            # create random PyTorch tensors
            _A				:	Tuple       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase			,						torchify=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						torch.Tensor)

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