
"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()






class     _UpperCAmelCase(    a__      ,     unittest.TestCase	):
		lowercase__						=      KandinskyVaaImgaImgPipeline
		lowercase__						=      ['image_embeds', 'negative_image_embeds', 'image']
		lowercase__						=      [
		    'image_embeds',
		    'negative_image_embeds',
		    'image',
		]
		lowercase__						=      [
		    'generator',
		    'height',
		    'width',
		    'strength',
		    'guidance_scale',
		    'num_inference_steps',
		    'return_dict',
		    'guidance_scale',
		    'num_images_per_prompt',
		    'output_type',
		    'return_dict',
		]
		lowercase__						=      False



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






							'''simple docstring'''
							return 32



		@property
		def 						UpperCAmelCase							(					self)       ->       Dict:






							'''simple docstring'''
							return 32



		@property
		def 						UpperCAmelCase							(					self)       ->       Any:






							'''simple docstring'''
							return self.time_input_dim



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






							'''simple docstring'''
							return self.time_input_dim * 4



		@property
		def 						UpperCAmelCase							(					self)       ->       Tuple:






							'''simple docstring'''
							return 1_00



		@property
		def 						UpperCAmelCase							(					self)       ->       Optional[int]:






							'''simple docstring'''
							torch.manual_seed(0)

							_UpperCamelCase							 =  {
							    '''in_channels''': 4,
							    # Out channels is double in channels because predicts mean and variance
							    '''out_channels''': 8,
							    '''addition_embed_type''': '''image''',
							    '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
							    '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
							    '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
							    '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
							    '''layers_per_block''': 1,
							    '''encoder_hid_dim''': self.text_embedder_hidden_size,
							    '''encoder_hid_dim_type''': '''image_proj''',
							    '''cross_attention_dim''': self.cross_attention_dim,
							    '''attention_head_dim''': 4,
							    '''resnet_time_scale_shift''': '''scale_shift''',
							    '''class_embed_type''': None,
							}

							_UpperCamelCase							 =  UNetaDConditionModel(**UpperCamelCase_)
							return model



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






							'''simple docstring'''
							return {
							    "block_out_channels": [32, 64],
							    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
							    "in_channels": 3,
							    "latent_channels": 4,
							    "layers_per_block": 1,
							    "norm_num_groups": 8,
							    "norm_type": "spatial",
							    "num_vq_embeddings": 12,
							    "out_channels": 3,
							    "up_block_types": [
							        "AttnUpDecoderBlock2D",
							        "UpDecoderBlock2D",
							    ],
							    "vq_embed_dim": 4,
							}



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






							'''simple docstring'''
							torch.manual_seed(0)
							_UpperCamelCase							 =  VQModel(**self.dummy_movq_kwargs)
							return model



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






							'''simple docstring'''
							_UpperCamelCase							 =  self.dummy_unet
							_UpperCamelCase							 =  self.dummy_movq

							_UpperCamelCase							 =  {
							    '''num_train_timesteps''': 10_00,
							    '''beta_schedule''': '''linear''',
							    '''beta_start''': 0.0_0085,
							    '''beta_end''': 0.012,
							    '''clip_sample''': False,
							    '''set_alpha_to_one''': False,
							    '''steps_offset''': 0,
							    '''prediction_type''': '''epsilon''',
							    '''thresholding''': False,
							}

							_UpperCamelCase							 =  DDIMScheduler(**UpperCamelCase_)

							_UpperCamelCase							 =  {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''movq''': movq,
							}

							return components



		def 						UpperCAmelCase							(					self				,		__a				,		__a=0)       ->       Tuple:






							'''simple docstring'''
							_UpperCamelCase							 =  floats_tensor((1, self.text_embedder_hidden_size)				,		rng=random.Random(UpperCamelCase_)).to(UpperCamelCase_)
							_UpperCamelCase							 =  floats_tensor((1, self.text_embedder_hidden_size)				,		rng=random.Random(seed + 1)).to(
							    UpperCamelCase_)
							# create init_image
							_UpperCamelCase							 =  floats_tensor((1, 3, 64, 64)				,		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_56, 2_56))

							if str(UpperCamelCase_).startswith('''mps'''):
												_UpperCamelCase							 =  torch.manual_seed(UpperCamelCase_)
							else:
												_UpperCamelCase							 =  torch.Generator(device=UpperCamelCase_).manual_seed(UpperCamelCase_)
							_UpperCamelCase							 =  {
							    '''image''': init_image,
							    '''image_embeds''': image_embeds,
							    '''negative_image_embeds''': negative_image_embeds,
							    '''generator''': generator,
							    '''height''': 64,
							    '''width''': 64,
							    '''num_inference_steps''': 10,
							    '''guidance_scale''': 7.0,
							    '''strength''': 0.2,
							    '''output_type''': '''np''',
							}
							return inputs




		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''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.images

							_UpperCamelCase							 =  pipe(
							    **self.get_dummy_inputs(UpperCamelCase_)				,		return_dict=UpperCamelCase_				,		)[0]

							_UpperCamelCase							 =  image[0, -3:, -3:, -1]
							_UpperCamelCase							 =  image_from_tuple[0, -3:, -3:, -1]

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

							_UpperCamelCase							 =  np.array(
							    [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263])
							assert (
							    np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
							), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
							assert (
							    np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
							), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''






@slow
@require_torch_gpu
class     _UpperCAmelCase(    unittest.TestCase	):



		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()




		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase							 =  load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/kandinskyv22/kandinskyv22_img2img_frog.npy''')

							_UpperCamelCase							 =  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''')
							_UpperCamelCase							 =  '''A red cartoon frog, 4k'''

							_UpperCamelCase							 =  KandinskyVaaPriorPipeline.from_pretrained(
							    '''kandinsky-community/kandinsky-2-2-prior'''				,		torch_dtype=torch.floataa)
							pipe_prior.to(UpperCamelCase_)

							_UpperCamelCase							 =  KandinskyVaaImgaImgPipeline.from_pretrained(
							    '''kandinsky-community/kandinsky-2-2-decoder'''				,		torch_dtype=torch.floataa)
							_UpperCamelCase							 =  pipeline.to(UpperCamelCase_)

							pipeline.set_progress_bar_config(disable=UpperCamelCase_)

							_UpperCamelCase							 =  torch.Generator(device='''cpu''').manual_seed(0)
							_UpperCamelCase							 =  pipe_prior(
							    UpperCamelCase_				,		generator=UpperCamelCase_				,		num_inference_steps=5				,		negative_prompt=''''''				,		).to_tuple()

							_UpperCamelCase							 =  pipeline(
							    image=UpperCamelCase_				,		image_embeds=UpperCamelCase_				,		negative_image_embeds=UpperCamelCase_				,		generator=UpperCamelCase_				,		num_inference_steps=1_00				,		height=7_68				,		width=7_68				,		strength=0.2				,		output_type='''np'''				,		)

							_UpperCamelCase							 =  output.images[0]

							assert image.shape == (7_68, 7_68, 3)

							assert_mean_pixel_difference(UpperCamelCase_				,		UpperCamelCase_)










"""simple docstring"""





import math


def    _snake_case  (  ):
      lowerCAmelCase    :		Union[str, Any]				=      input('''Enter message: '''	)
      lowerCAmelCase    :		Optional[int]				=      int(input(f'''Enter key [2-{len(_snake_case	) - 1}]: '''	)	)
      lowerCAmelCase    :		str				=      input('''Encryption/Decryption [e/d]: '''	)

      if mode.lower().startswith('''e'''	):
            lowerCAmelCase    :		Any				=      encrypt_message(_snake_case       ,      _snake_case	)
      elif mode.lower().startswith('''d'''	):
            lowerCAmelCase    :		Union[str, Any]				=      decrypt_message(_snake_case       ,      _snake_case	)

      # Append pipe symbol (vertical bar) to identify spaces at the end.
      print(f'''Output:\n{text + "|"}'''	)


def    _snake_case  (  _snake_case :	int       ,      _snake_case :	str	):
      lowerCAmelCase    :		Optional[Any]				=      [''''''] * key
      for col in range(_snake_case	):
            lowerCAmelCase    :		Optional[Any]				=      col
            while pointer < len(_snake_case	):
                  cipher_text[col] += message[pointer]
                  pointer += key
      return "".join(_snake_case	)


def    _snake_case  (  _snake_case :	int       ,      _snake_case :	str	):
      lowerCAmelCase    :		Union[str, Any]				=      math.ceil(len(_snake_case	) / key	)
      lowerCAmelCase    :		str				=      key
      lowerCAmelCase    :		Any				=      (num_cols * num_rows) - len(_snake_case	)
      lowerCAmelCase    :		Dict				=      [''''''] * num_cols
      lowerCAmelCase    :		int				=      0
      lowerCAmelCase    :		int				=      0

      for symbol in message:
            plain_text[col] += symbol
            col += 1

            if (
                (col == num_cols)
                or (col == num_cols - 1)
                and (row >= num_rows - num_shaded_boxes)
            ):
                  lowerCAmelCase    :		int				=      0
                  row += 1

      return "".join(_snake_case	)


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 main()


