






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 	a_(		lowercase__			,							unittest.TestCase	):



     """simple docstring"""



     __snake_case		:				List[Any]  					=KandinskyVaaPriorEmbaEmbPipeline
     __snake_case		:				Any  					=['''prompt''', '''image''']
     __snake_case		:				List[str]  					=['''prompt''', '''image''']
     __snake_case		:				Dict  					=[
         '''num_images_per_prompt''',
         '''strength''',
         '''generator''',
         '''num_inference_steps''',
         '''latents''',
         '''negative_prompt''',
         '''guidance_scale''',
         '''output_type''',
         '''return_dict''',
     ]
     __snake_case		:				List[Any]  					=False





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

      """simple docstring"""
      return 3_2





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

      """simple docstring"""
      return 3_2





     @property
     def     __UpperCamelCase						(		self					:	Tuple)							->	Any:

      """simple docstring"""
      return self.time_input_dim





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

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





     @property
     def     __UpperCamelCase						(		self					:	List[str])							->	Optional[int]:

      """simple docstring"""
      return 1_0_0





     @property
     def     __UpperCamelCase						(		self					:	str)							->	str:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
      return tokenizer





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

      """simple docstring"""
      torch.manual_seed(0)
      SCREAMING_SNAKE_CASE				    =		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     __UpperCamelCase						(		self					:	List[Any])							->	Tuple:

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

      SCREAMING_SNAKE_CASE				    =		{
          'num_attention_heads': 2,
          'attention_head_dim': 1_2,
          'embedding_dim': self.text_embedder_hidden_size,
          'num_layers': 1,
      }

      SCREAMING_SNAKE_CASE				    =		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
      SCREAMING_SNAKE_CASE				    =		nn.Parameter(torch.ones(model.clip_std.shape))
      return model





     @property
     def     __UpperCamelCase						(		self					:	int)							->	Tuple:

      """simple docstring"""
      torch.manual_seed(0)
      SCREAMING_SNAKE_CASE				    =		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  ,  )

      SCREAMING_SNAKE_CASE				    =		CLIPVisionModelWithProjection(lowerCAmelCase__)
      return model





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

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		CLIPImageProcessor(
          crop_size=2_2_4  ,  do_center_crop=lowerCAmelCase__  ,  do_normalize=lowerCAmelCase__  ,  do_resize=lowerCAmelCase__  ,  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     __UpperCamelCase						(		self					:	Optional[Any])							->	List[str]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		self.dummy_prior
      SCREAMING_SNAKE_CASE				    =		self.dummy_image_encoder
      SCREAMING_SNAKE_CASE				    =		self.dummy_text_encoder
      SCREAMING_SNAKE_CASE				    =		self.dummy_tokenizer
      SCREAMING_SNAKE_CASE				    =		self.dummy_image_processor

      SCREAMING_SNAKE_CASE				    =		UnCLIPScheduler(
          variance_type='fixed_small_log'  ,  prediction_type='sample'  ,  num_train_timesteps=1_0_0_0  ,  clip_sample=lowerCAmelCase__  ,  clip_sample_range=10.0  ,  )

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

      return components





     def     __UpperCamelCase						(		self					:	List[Any]  ,  lowerCAmelCase__					:	Dict  ,  lowerCAmelCase__					:	Any=0)							->	int:

      """simple docstring"""
      if str(lowerCAmelCase__).startswith('mps'):
       SCREAMING_SNAKE_CASE				    =		torch.manual_seed(lowerCAmelCase__)
      else:
       SCREAMING_SNAKE_CASE				    =		torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)

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

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





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

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		'cpu'

      SCREAMING_SNAKE_CASE				    =		self.get_dummy_components()

      SCREAMING_SNAKE_CASE				    =		self.pipeline_class(**lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		pipe.to(lowerCAmelCase__)

      pipe.set_progress_bar_config(disable=lowerCAmelCase__)

      SCREAMING_SNAKE_CASE				    =		pipe(**self.get_dummy_inputs(lowerCAmelCase__))
      SCREAMING_SNAKE_CASE				    =		output.image_embeds

      SCREAMING_SNAKE_CASE				    =		pipe(
          **self.get_dummy_inputs(lowerCAmelCase__)  ,  return_dict=lowerCAmelCase__  ,  )[0]

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

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

      SCREAMING_SNAKE_CASE				    =		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     __UpperCamelCase						(		self					:	Union[str, Any])							->	Union[str, Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		torch_device == 'cpu'
      SCREAMING_SNAKE_CASE				    =		True
      SCREAMING_SNAKE_CASE				    =		False

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





     @skip_mps
     def     __UpperCamelCase						(		self					:	Union[str, Any])							->	Union[str, Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		torch_device == 'cpu'
      SCREAMING_SNAKE_CASE				    =		False

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












"""simple docstring"""
from itertools import combinations, product






def 			lowerCamelCase_    (		_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							):
 if xa == ya == 0 or xa == ya == 0:
  return False
 lowerCamelCase__	:     Tuple								=		xa * xa + ya * ya
 lowerCamelCase__	:     Union[str, Any]								=		xa * xa + ya * ya
 lowerCamelCase__	:     Optional[Any]								=		(xa - xa) * (xa - xa) + (ya - ya) * (ya - ya)
 return (
     a_square + b_square == c_square
     or a_square + c_square == b_square
     or b_square + c_square == a_square
 )






def 			lowerCamelCase_    (		_lowerCamelCase = 50							):
 return sum(
     1
     for pta, pta in combinations(product(range(limit + 1							)     ,  repeat=2							)     ,  2							)
     if is_right(*_lowerCamelCase     ,  *_lowerCamelCase							)							)


if __name__ == "__main__":
      print(f"{solution() = }")

