






"""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 						snake_case  (  UpperCAmelCase   , unittest.TestCase       ):
    __magic_name__         =     KandinskyVaaPriorEmbaEmbPipeline
    __magic_name__         =     ['''prompt''', '''image''']
    __magic_name__         =     ['''prompt''', '''image''']
    __magic_name__         =     [
        '''num_images_per_prompt''',
        '''strength''',
        '''generator''',
        '''num_inference_steps''',
        '''latents''',
        '''negative_prompt''',
        '''guidance_scale''',
        '''output_type''',
        '''return_dict''',
    ]
    __magic_name__         =     False





    @property
    def 				lowerCamelCase__      (							self	:					Optional[Any]			):


      '''simple docstring'''




      return 3_2





    @property
    def 				lowerCamelCase__      (							self	:					Optional[Any]			):


      '''simple docstring'''




      return 3_2





    @property
    def 				lowerCamelCase__      (							self	:					Optional[Any]			):


      '''simple docstring'''




      return self.time_input_dim





    @property
    def 				lowerCamelCase__      (							self	:					Any			):


      '''simple docstring'''




      return self.time_input_dim * 4





    @property
    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      return 1_0_0





    @property
    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




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





    @property
    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




      torch.manual_seed(0			)
      a     :			Dict				=   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(A			)





    @property
    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      torch.manual_seed(0			)

      a     :			Union[str, Any]				=   {
          'num_attention_heads': 2,
          'attention_head_dim': 1_2,
          'embedding_dim': self.text_embedder_hidden_size,
          'num_layers': 1,
      }

      a     :			Optional[int]				=   PriorTransformer(**A			)
      # 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
      a     :			Optional[Any]				=   nn.Parameter(torch.ones(model.clip_std.shape			)			)
      return model





    @property
    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      torch.manual_seed(0			)
      a     :			Any				=   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				,		)

      a     :			int				=   CLIPVisionModelWithProjection(A			)
      return model





    @property
    def 				lowerCamelCase__      (							self	:					Optional[Any]			):


      '''simple docstring'''




      a     :			str				=   CLIPImageProcessor(
          crop_size=2_2_4				,		do_center_crop=A				,		do_normalize=A				,		do_resize=A				,		image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]				,		image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]				,		resample=3				,		size=2_2_4				,		)

      return image_processor





    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      a     :			Union[str, Any]				=   self.dummy_prior
      a     :			str				=   self.dummy_image_encoder
      a     :			Optional[int]				=   self.dummy_text_encoder
      a     :			int				=   self.dummy_tokenizer
      a     :			Dict				=   self.dummy_image_processor

      a     :			Any				=   UnCLIPScheduler(
          variance_type='fixed_small_log'				,		prediction_type='sample'				,		num_train_timesteps=1_0_0_0				,		clip_sample=A				,		clip_sample_range=10.0				,		)

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

      return components





    def 				lowerCamelCase__      (							self	:					Any				,		A	:					Dict				,		A	:					Any=0			):


      '''simple docstring'''




      if str(A			).startswith('mps'			):
        a     :			str				=   torch.manual_seed(A			)
      else:
        a     :			Dict				=   torch.Generator(device=A			).manual_seed(A			)

      a     :			int				=   floats_tensor((1, 3, 6_4, 6_4)				,		rng=random.Random(A			)			).to(A			)
      a     :			Optional[Any]				=   image.cpu().permute(0				,		2				,		3				,		1			)[0]
      a     :			List[Any]				=   Image.fromarray(np.uinta(A			)			).convert('RGB'			).resize((2_5_6, 2_5_6)			)

      a     :			Optional[int]				=   {
          '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'''




      a     :			int				=   'cpu'

      a     :			Union[str, Any]				=   self.get_dummy_components()

      a     :			Union[str, Any]				=   self.pipeline_class(**A			)
      a     :			Tuple				=   pipe.to(A			)

      pipe.set_progress_bar_config(disable=A			)

      a     :			List[str]				=   pipe(**self.get_dummy_inputs(A			)			)
      a     :			List[str]				=   output.image_embeds

      a     :			Union[str, Any]				=   pipe(
          **self.get_dummy_inputs(A			)				,		return_dict=A				,		)[0]

      a     :			Optional[Any]				=   image[0, -1_0:]
      a     :			Any				=   image_from_tuple[0, -1_0:]

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

      a     :			Tuple				=   np.array(
          [
              0.1_07_12_84,
              1.3_33_02_71,
              0.61_26_02_23,
              -0.6_69_10_65,
              -0.3_84_68_52,
              -1.0_30_36_61,
              0.22_71_61_11,
              0.03_34_89_01,
              0.30_04_06_75,
              -0.24_80_50_29,
          ]			)

      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	:					Union[str, Any]			):


      '''simple docstring'''




      a     :			int				=   torch_device == 'cpu'
      a     :			Any				=   True
      a     :			Union[str, Any]				=   False

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





    @skip_mps
    def 				lowerCamelCase__      (							self	:					Union[str, Any]			):


      '''simple docstring'''




      a     :			List[Any]				=   torch_device == 'cpu'
      a     :			int				=   False

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











from typing import Literal

UpperCamelCase__          ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase,				__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		Tuple  			=							LETTERS if mode == "decrypt" else key
     _SCREAMING_SNAKE_CASE				:		Tuple  			=							key if mode == "decrypt" else LETTERS
     _SCREAMING_SNAKE_CASE				:		Dict  			=							""
     # loop through each symbol in the message
     for symbol in message:
          if symbol.upper() in chars_a:
               # encrypt/decrypt the symbol
               _SCREAMING_SNAKE_CASE				:		List[str]  			=							chars_a.find(symbol.upper()		)
               if symbol.isupper():
                    translated += chars_b[sym_index].upper()
               else:
                    translated += chars_b[sym_index].lower()
          else:
               # symbol is not in LETTERS, just add it
               translated += symbol
     return translated






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase		):
     return translate_message(__lowerCamelCase,				__lowerCamelCase,				"encrypt"		)






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase		):
     return translate_message(__lowerCamelCase,				__lowerCamelCase,				"decrypt"		)






def 			lowerCamelCase__	():
     _SCREAMING_SNAKE_CASE				:		str  			=							"Hello World"
     _SCREAMING_SNAKE_CASE				:		List[str]  			=							"QWERTYUIOPASDFGHJKLZXCVBNM"
     _SCREAMING_SNAKE_CASE				:		Any  			=							"decrypt"  # set to 'encrypt' or 'decrypt'

     if mode == "encrypt":
          _SCREAMING_SNAKE_CASE				:		int  			=							encrypt_message(__lowerCamelCase,				__lowerCamelCase		)
     elif mode == "decrypt":
          _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							decrypt_message(__lowerCamelCase,				__lowerCamelCase		)
     print(f"""Using the key {key}, the {mode}ed message is: {translated}"""		)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       main()