




import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class        _UpperCamelCase				(						lowerCAmelCase_						,unittest.TestCase			):


			"""simple docstring"""






			__a  :			Any      			=						KandinskyPriorPipeline
			__a  :			Optional[Any]      			=						['''prompt''']
			__a  :			List[Any]      			=						['''prompt''', '''negative_prompt''']
			__a  :			Optional[Any]      			=						[
			    '''num_images_per_prompt''',
			    '''generator''',
			    '''num_inference_steps''',
			    '''latents''',
			    '''negative_prompt''',
			    '''guidance_scale''',
			    '''output_type''',
			    '''return_dict''',
			]
			__a  :			Optional[Any]      			=						False





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> int:

							'''simple docstring'''


							return 32





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> int:

							'''simple docstring'''


							return 32





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

							'''simple docstring'''


							return self.time_input_dim





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> str:

							'''simple docstring'''


							return self.time_input_dim * 4





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

							'''simple docstring'''


							return 1_00





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

							'''simple docstring'''


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





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

							'''simple docstring'''


							torch.manual_seed(0						)
							__lowercase			      =							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=37				,       layer_norm_eps=1E-05				,       num_attention_heads=4				,       num_hidden_layers=5				,       pad_token_id=1				,       vocab_size=10_00				,       )
							return CLIPTextModelWithProjection(_snake_case						)





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> int:

							'''simple docstring'''


							torch.manual_seed(0						)

							__lowercase			      =							{
							    'num_attention_heads': 2,
							    'attention_head_dim': 12,
							    'embedding_dim': self.text_embedder_hidden_size,
							    'num_layers': 1,
							}

							__lowercase			      =							PriorTransformer(**_snake_case						)
							# 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
							__lowercase			      =							nn.Parameter(torch.ones(model.clip_std.shape						)						)
							return model





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

							'''simple docstring'''


							torch.manual_seed(0						)
							__lowercase			      =							CLIPVisionConfig(
							    hidden_size=self.text_embedder_hidden_size				,       image_size=2_24				,       projection_dim=self.text_embedder_hidden_size				,       intermediate_size=37				,       num_attention_heads=4				,       num_channels=3				,       num_hidden_layers=5				,       patch_size=14				,       )

							__lowercase			      =							CLIPVisionModelWithProjection(_snake_case						)
							return model





			@property
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> Tuple:

							'''simple docstring'''


							__lowercase			      =							CLIPImageProcessor(
							    crop_size=2_24				,       do_center_crop=_snake_case				,       do_normalize=_snake_case				,       do_resize=_snake_case				,       image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]				,       image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]				,       resample=3				,       size=2_24				,       )

							return image_processor





			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[Any]:

							'''simple docstring'''


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

							__lowercase			      =							UnCLIPScheduler(
							    variance_type='''fixed_small_log'''				,       prediction_type='''sample'''				,       num_train_timesteps=10_00				,       clip_sample=_snake_case				,       clip_sample_range=10.0				,       )

							__lowercase			      =							{
							    'prior': prior,
							    'image_encoder': image_encoder,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'scheduler': scheduler,
							    'image_processor': image_processor,
							}

							return components





			def 	_SCREAMING_SNAKE_CASE      (       self				,       lowerCAmelCase__				,       lowerCAmelCase__=0						)					-> Tuple:

							'''simple docstring'''


							if str(_snake_case						).startswith('''mps'''						):
											__lowercase			      =							torch.manual_seed(_snake_case						)
							else:
											__lowercase			      =							torch.Generator(device=_snake_case						).manual_seed(_snake_case						)
							__lowercase			      =							{
							    'prompt': 'horse',
							    'generator': generator,
							    'guidance_scale': 4.0,
							    'num_inference_steps': 2,
							    'output_type': 'np',
							}
							return inputs





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

							'''simple docstring'''


							__lowercase			      =							'cpu'

							__lowercase			      =							self.get_dummy_components()

							__lowercase			      =							self.pipeline_class(**_snake_case						)
							__lowercase			      =							pipe.to(_snake_case						)

							pipe.set_progress_bar_config(disable=_snake_case						)

							__lowercase			      =							pipe(**self.get_dummy_inputs(_snake_case						)						)
							__lowercase			      =							output.image_embeds

							__lowercase			      =							pipe(
							    **self.get_dummy_inputs(_snake_case						)				,       return_dict=_snake_case				,       )[0]

							__lowercase			      =							image[0, -10:]
							__lowercase			      =							image_from_tuple[0, -10:]

							assert image.shape == (1, 32)

							__lowercase			      =							np.array(
							    [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]						)

							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 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[str]:

							'''simple docstring'''


							__lowercase			      =							torch_device == 'cpu'
							__lowercase			      =							True
							__lowercase			      =							False

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





			@skip_mps
			def 	_SCREAMING_SNAKE_CASE      (       self						)					-> List[Any]:

							'''simple docstring'''


							__lowercase			      =							torch_device == 'cpu'
							__lowercase			      =							False

							self._test_attention_slicing_forward_pass(
							    test_max_difference=_snake_case				,       test_mean_pixel_difference=_snake_case				,       )
import os
import sys

from . import rsa_key_generator as rkg

__a  :					Union[str, Any]          =  1_2_8
__a  :					List[str]          =  2_5_6





def     UpperCAmelCase						(   lowercase							,      lowercase = DEFAULT_BLOCK_SIZE							):







				"""simple docstring"""



				__lowercase			      =							message.encode('''ascii'''							)

				__lowercase			      =							[]
				for block_start in range(0							,      len(lowercase							)							,      lowercase							):
								__lowercase			      =							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"""



				__lowercase			      =							[]
				for block_int in block_ints:
								__lowercase			      =							[]
								for i in range(block_size - 1							,      -1							,      -1							):
												if len(lowercase							) + i < message_length:
																__lowercase			      =							block_int // (BYTE_SIZE**i)
																__lowercase			      =							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"""



				__lowercase			      =							[]
				__lowercase      ,					__lowercase			      =							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"""



				__lowercase			      =							[]
				__lowercase      ,					__lowercase			      =							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:
								__lowercase			      =							fo.read()
				__lowercase      ,					__lowercase      ,					__lowercase			      =							content.split(''','''							)
				return (int(lowercase							), int(lowercase							), int(lowercase							))





def     UpperCAmelCase						(   lowercase							,      lowercase							,      lowercase							,      lowercase = DEFAULT_BLOCK_SIZE							,      ):







				"""simple docstring"""



				__lowercase      ,					__lowercase      ,					__lowercase			      =							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							)							)

				__lowercase			      =							[str(lowercase							) for i in encrypt_message(lowercase							,      (n, e)							,      lowercase							)]

				__lowercase			      =							''','''.join(lowercase							)
				__lowercase			      =							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"""



				__lowercase      ,					__lowercase      ,					__lowercase			      =							read_key_file(lowercase							)
				with open(lowercase							) as fo:
								__lowercase			      =							fo.read()
				__lowercase      ,					__lowercase      ,					__lowercase			      =							content.split('''_'''							)
				__lowercase			      =							int(lowercase							)
				__lowercase			      =							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							)							)

				__lowercase			      =							[]
				for block in encrypted_message.split(''','''							):
								encrypted_blocks.append(int(lowercase							)							)

				return decrypt_message(lowercase							,      lowercase							,      (n, d)							,      lowercase							)





def     UpperCAmelCase						(   ):







				"""simple docstring"""



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

				if response.lower().startswith('''e'''							):
								__lowercase			      =							'''encrypt'''
				elif response.lower().startswith('''d'''							):
								__lowercase			      =							'''decrypt'''

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

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

								print('''\nEncrypted text:'''							)
								print(lowercase							)

				elif mode == "decrypt":
								__lowercase			      =							'''rsa_privkey.txt'''
								print(F"Reading from {filename} and decrypting..."							)
								__lowercase			      =							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()