'''simple docstring'''

import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 							lowercase_    (     _A ,  unittest.TestCase						):
    a_             =   KandinskyVaaPriorEmbaEmbPipeline
    a_             =   ["""prompt""", """image"""]
    a_             =   ["""prompt""", """image"""]
    a_             =   [
        """num_images_per_prompt""",
        """strength""",
        """generator""",
        """num_inference_steps""",
        """latents""",
        """negative_prompt""",
        """guidance_scale""",
        """output_type""",
        """return_dict""",
    ]
    a_             =   False







    @property
    def   lowerCamelCase_    (	self				)				->       str:





     """simple docstring"""

     return 3_2







    @property
    def   lowerCamelCase_    (	self				)				->       List[Any]:





     """simple docstring"""

     return 3_2







    @property
    def   lowerCamelCase_    (	self				)				->       List[str]:





     """simple docstring"""

     return self.time_input_dim







    @property
    def   lowerCamelCase_    (	self				)				->       Optional[Any]:





     """simple docstring"""

     return self.time_input_dim * 4







    @property
    def   lowerCamelCase_    (	self				)				->       str:





     """simple docstring"""

     return 1_0_0







    @property
    def   lowerCamelCase_    (	self				)				->       int:





     """simple docstring"""

     UpperCAmelCase_				       =					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"				)
     return tokenizer







    @property
    def   lowerCamelCase_    (	self				)				->       Union[str, Any]:





     """simple docstring"""

     torch.manual_seed(0				)
     UpperCAmelCase_				       =					CLIPTextConfig(
         bos_token_id=0       ,     eos_token_id=2       ,     hidden_size=self.text_embedder_hidden_size       ,     projection_dim=self.text_embedder_hidden_size       ,     intermediate_size=3_7       ,     layer_norm_eps=1e-05       ,     num_attention_heads=4       ,     num_hidden_layers=5       ,     pad_token_id=1       ,     vocab_size=1_0_0_0       ,     )
     return CLIPTextModelWithProjection(UpperCamelCase__				)







    @property
    def   lowerCamelCase_    (	self				)				->       List[str]:





     """simple docstring"""

     torch.manual_seed(0				)

     UpperCAmelCase_				       =					{
         "num_attention_heads": 2,
         "attention_head_dim": 1_2,
         "embedding_dim": self.text_embedder_hidden_size,
         "num_layers": 1,
     }

     UpperCAmelCase_				       =					PriorTransformer(**UpperCamelCase__				)
     # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
     UpperCAmelCase_				       =					nn.Parameter(torch.ones(model.clip_std.shape				)				)
     return model







    @property
    def   lowerCamelCase_    (	self				)				->       Optional[Any]:





     """simple docstring"""

     torch.manual_seed(0				)
     UpperCAmelCase_				       =					CLIPVisionConfig(
         hidden_size=self.text_embedder_hidden_size       ,     image_size=2_2_4       ,     projection_dim=self.text_embedder_hidden_size       ,     intermediate_size=3_7       ,     num_attention_heads=4       ,     num_channels=3       ,     num_hidden_layers=5       ,     patch_size=1_4       ,     )

     UpperCAmelCase_				       =					CLIPVisionModelWithProjection(UpperCamelCase__				)
     return model







    @property
    def   lowerCamelCase_    (	self				)				->       Union[str, Any]:





     """simple docstring"""

     UpperCAmelCase_				       =					CLIPImageProcessor(
         crop_size=2_2_4       ,     do_center_crop=UpperCamelCase__       ,     do_normalize=UpperCamelCase__       ,     do_resize=UpperCamelCase__       ,     image_mean=[0.48145466, 0.4578275, 0.40821073]       ,     image_std=[0.26862954, 0.26130258, 0.27577711]       ,     resample=3       ,     size=2_2_4       ,     )

     return image_processor







    def   lowerCamelCase_    (	self				)				->       str:





     """simple docstring"""

     UpperCAmelCase_				       =					self.dummy_prior
     UpperCAmelCase_				       =					self.dummy_image_encoder
     UpperCAmelCase_				       =					self.dummy_text_encoder
     UpperCAmelCase_				       =					self.dummy_tokenizer
     UpperCAmelCase_				       =					self.dummy_image_processor

     UpperCAmelCase_				       =					UnCLIPScheduler(
         variance_type="fixed_small_log"       ,     prediction_type="sample"       ,     num_train_timesteps=1_0_0_0       ,     clip_sample=UpperCamelCase__       ,     clip_sample_range=10.0       ,     )

     UpperCAmelCase_				       =					{
         "prior": prior,
         "image_encoder": image_encoder,
         "text_encoder": text_encoder,
         "tokenizer": tokenizer,
         "scheduler": scheduler,
         "image_processor": image_processor,
     }

     return components







    def   lowerCamelCase_    (	self       ,     UpperCamelCase__       ,     UpperCamelCase__=0				)				->       Union[str, Any]:





     """simple docstring"""

     if str(UpperCamelCase__				).startswith("mps"				):
      UpperCAmelCase_				       =					torch.manual_seed(UpperCamelCase__				)
     else:
      UpperCAmelCase_				       =					torch.Generator(device=UpperCamelCase__				).manual_seed(UpperCamelCase__				)

     UpperCAmelCase_				       =					floats_tensor((1, 3, 6_4, 6_4)       ,     rng=random.Random(UpperCamelCase__				)				).to(UpperCamelCase__				)
     UpperCAmelCase_				       =					image.cpu().permute(0       ,     2       ,     3       ,     1				)[0]
     UpperCAmelCase_				       =					Image.fromarray(np.uinta(UpperCamelCase__				)				).convert("RGB"				).resize((2_5_6, 2_5_6)				)

     UpperCAmelCase_				       =					{
         "prompt": "horse",
         "image": init_image,
         "strength": 0.5,
         "generator": generator,
         "guidance_scale": 4.0,
         "num_inference_steps": 2,
         "output_type": "np",
     }
     return inputs







    def   lowerCamelCase_    (	self				)				->       Optional[int]:





     """simple docstring"""

     UpperCAmelCase_				       =					"cpu"

     UpperCAmelCase_				       =					self.get_dummy_components()

     UpperCAmelCase_				       =					self.pipeline_class(**UpperCamelCase__				)
     UpperCAmelCase_				       =					pipe.to(UpperCamelCase__				)

     pipe.set_progress_bar_config(disable=UpperCamelCase__				)

     UpperCAmelCase_				       =					pipe(**self.get_dummy_inputs(UpperCamelCase__				)				)
     UpperCAmelCase_				       =					output.image_embeds

     UpperCAmelCase_				       =					pipe(
         **self.get_dummy_inputs(UpperCamelCase__				)       ,     return_dict=UpperCamelCase__       ,     )[0]

     UpperCAmelCase_				       =					image[0, -1_0:]
     UpperCAmelCase_				       =					image_from_tuple[0, -1_0:]

     assert image.shape == (1, 3_2)

     UpperCAmelCase_				       =					np.array(
         [
             0.1071284,
             1.3330271,
             0.61260223,
             -0.6691065,
             -0.3846852,
             -1.0303661,
             0.22716111,
             0.03348901,
             0.30040675,
             -0.24805029,
         ]				)

     assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1e-2







    @skip_mps
    def   lowerCamelCase_    (	self				)				->       Optional[int]:





     """simple docstring"""

     UpperCAmelCase_				       =					torch_device == "cpu"
     UpperCAmelCase_				       =					True
     UpperCAmelCase_				       =					False

     self._test_inference_batch_single_identical(
         test_max_difference=UpperCamelCase__       ,     relax_max_difference=UpperCamelCase__       ,     test_mean_pixel_difference=UpperCamelCase__       ,     )







    @skip_mps
    def   lowerCamelCase_    (	self				)				->       Optional[Any]:





     """simple docstring"""

     UpperCAmelCase_				       =					torch_device == "cpu"
     UpperCAmelCase_				       =					False

     self._test_attention_slicing_forward_pass(
         test_max_difference=UpperCamelCase__       ,     test_mean_pixel_difference=UpperCamelCase__       ,     )

'''simple docstring'''

import os
import sys

from . import rsa_key_generator as rkg

__snake_case       :   Dict  		=    1_28
__snake_case       :   Union[str, Any]  		=    2_56



def lowerCamelCase__						(       A_       ,			A_ = DEFAULT_BLOCK_SIZE       ):
 UpperCAmelCase_				       =					message.encode("ascii"       )

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



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



def lowerCamelCase__						(       A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ):
 UpperCAmelCase_				       =					[]
 UpperCAmelCase_       ,       UpperCAmelCase_				       =					key

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



def lowerCamelCase__						(       A_       ,			A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ,			):
 UpperCAmelCase_				       =					[]
 UpperCAmelCase_       ,       UpperCAmelCase_				       =					key
 for block in encrypted_blocks:
  decrypted_blocks.append(pow(A_       ,			A_       ,			A_       )       )
 return get_text_from_blocks(A_       ,			A_       ,			A_       )



def lowerCamelCase__						(       A_       ):
 with open(A_       ) as fo:
  UpperCAmelCase_				       =					fo.read()
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					content.split(","       )
 return (int(A_       ), int(A_       ), int(A_       ))



def lowerCamelCase__						(       A_       ,			A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ,			):
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					read_key_file(A_       )
 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       ,			A_       )       )

 UpperCAmelCase_				       =					[str(A_       ) for i in encrypt_message(A_       ,			(n, e)       ,			A_       )]

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



def lowerCamelCase__						(       A_       ,			A_       ):
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					read_key_file(A_       )
 with open(A_       ) as fo:
  UpperCAmelCase_				       =					fo.read()
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					content.split("_"       )
 UpperCAmelCase_				       =					int(A_       )
 UpperCAmelCase_				       =					int(A_       )

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

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

 return decrypt_message(A_       ,			A_       ,			(n, d)       ,			A_       )



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

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

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

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

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

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

  print("\nDecryption:"       )
  print(A_       )


if __name__ == "__main__":
      main()
