



'''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 						UpperCAmelCase						(		__a       ,						unittest.TestCase):


 '''simple docstring'''




 __magic_name__       :			Union[str, Any]	=   KandinskyVaaPriorEmbaEmbPipeline
 __magic_name__       :			Optional[Any]	=   ["prompt", "image"]
 __magic_name__       :			Tuple	=   ["prompt", "image"]
 __magic_name__       :			Tuple	=   [
     "num_images_per_prompt",
     "strength",
     "generator",
     "num_inference_steps",
     "latents",
     "negative_prompt",
     "guidance_scale",
     "output_type",
     "return_dict",
 ]
 __magic_name__       :			List[str]	=   False




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



      """simple docstring"""







      return 3_2




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



      """simple docstring"""







      return 3_2




 @property
 def    lowercase_	( self)			->   Dict:



      """simple docstring"""







      return self.time_input_dim




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



      """simple docstring"""







      return self.time_input_dim * 4




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



      """simple docstring"""







      return 1_0_0




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



      """simple docstring"""







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




 @property
 def    lowercase_	( self)			->   Dict:



      """simple docstring"""







      torch.manual_seed(0)
      a_									=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(lowerCAmelCase_)




 @property
 def    lowercase_	( self)			->   Any:



      """simple docstring"""







      torch.manual_seed(0)

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

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




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



      """simple docstring"""







      torch.manual_seed(0)
      a_									=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_									=CLIPVisionModelWithProjection(lowerCAmelCase_)
      return model




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



      """simple docstring"""







      a_									=CLIPImageProcessor(
          crop_size=2_2_4				,	do_center_crop=lowerCAmelCase_				,	do_normalize=lowerCAmelCase_				,	do_resize=lowerCAmelCase_				,	image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]				,	image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]				,	resample=3				,	size=2_2_4				,	)

      return image_processor




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



      """simple docstring"""







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

      a_									=UnCLIPScheduler(
          variance_type="fixed_small_log"				,	prediction_type="sample"				,	num_train_timesteps=1_0_0_0				,	clip_sample=lowerCAmelCase_				,	clip_sample_range=1_0.0				,	)

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

      return components




 def    lowercase_	( self				,	lowerCAmelCase_				,	lowerCAmelCase_=0)			->   Union[str, Any]:



      """simple docstring"""







      if str(lowerCAmelCase_).startswith("mps"):
           a_									=torch.manual_seed(lowerCAmelCase_)
      else:
           a_									=torch.Generator(device=lowerCAmelCase_).manual_seed(lowerCAmelCase_)

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

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




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



      """simple docstring"""







      a_									="cpu"

      a_									=self.get_dummy_components()

      a_									=self.pipeline_class(**lowerCAmelCase_)
      a_									=pipe.to(lowerCAmelCase_)

      pipe.set_progress_bar_config(disable=lowerCAmelCase_)

      a_									=pipe(**self.get_dummy_inputs(lowerCAmelCase_))
      a_									=output.image_embeds

      a_									=pipe(
          **self.get_dummy_inputs(lowerCAmelCase_)				,	return_dict=lowerCAmelCase_				,	)[0]

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

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

      a_									=np.array(
          [
              0.1_0_7_1_2_8_4,
              1.3_3_3_0_2_7_1,
              0.6_1_2_6_0_2_2_3,
              -0.6_6_9_1_0_6_5,
              -0.3_8_4_6_8_5_2,
              -1.0_3_0_3_6_6_1,
              0.2_2_7_1_6_1_1_1,
              0.0_3_3_4_8_9_0_1,
              0.3_0_0_4_0_6_7_5,
              -0.2_4_8_0_5_0_2_9,
          ])

      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    lowercase_	( self)			->   Any:



      """simple docstring"""







      a_									=torch_device == "cpu"
      a_									=True
      a_									=False

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




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



      """simple docstring"""







      a_									=torch_device == "cpu"
      a_									=False

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







'''simple docstring'''


lowercase											=      (1, 153, 370, 371, 1_634, 24_678_051, 115_132_219_018_763_992_565_095_597_973_971_522_401)
lowercase											=      (-153, -1, 0, 1.2, 200, "A", [], {}, None)






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False

     # Initialization of sum and number of digits.
     a_									=0
     a_									=0
     a_									=n
     # Calculation of digits of the number
     while temp > 0:
          number_of_digits += 1
          temp //= 1_0
     # Dividing number into separate digits and find Armstrong number
     a_									=n
     while temp > 0:
          a_									=temp % 1_0
          total += rem**number_of_digits
          temp //= 1_0
     return n == total






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False

     # Init a "histogram" of the digits
     a_									=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
     a_									=0
     a_									=0
     a_									=n
     while temp > 0:
          a_		,    a_									=divmod(lowercase__							,						1_0							)
          digit_histogram[rem] += 1
          digit_total += 1

     for cnt, i in zip(lowercase__							,						range(len(lowercase__							)							)							):
          total += cnt * i**digit_total

     return n == total






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False
     a_									=len(str(lowercase__							)							)  # the power that all digits will be raised to
     # check if sum of each digit multiplied expo times is equal to number
     return n == sum(int(lowercase__							) ** expo for i in str(lowercase__							)							)






def 			UpperCAmelCase_							(		):


     '''simple docstring'''







     a_									=int(input("Enter an integer to see if it is an Armstrong number: "							).strip()							)
     print(F"""{num} is {'' if armstrong_number(lowercase__							) else 'not '}an Armstrong number."""							)
     print(F"""{num} is {'' if narcissistic_number(lowercase__							) else 'not '}an Armstrong number."""							)
     print(F"""{num} is {'' if pluperfect_number(lowercase__							) else 'not '}an Armstrong number."""							)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()


