
"""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 SCREAMING_SNAKE_CASE       (      lowerCAmelCase					,   unittest.TestCase					):






	'''simple docstring'''







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


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

			'''simple docstring'''






			return 32


	@property
	def    _UpperCamelCase							(  self :int			)			->   str:

			'''simple docstring'''






			return 32


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

			'''simple docstring'''






			return self.time_input_dim


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

			'''simple docstring'''






			return self.time_input_dim * 4


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

			'''simple docstring'''






			return 100


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

			'''simple docstring'''






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


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

			'''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=37       ,    layer_norm_eps=1e-05       ,    num_attention_heads=4       ,    num_hidden_layers=5       ,    pad_token_id=1       ,    vocab_size=1000       ,    )
			return CLIPTextModelWithProjection(__magic_name__			)


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

			'''simple docstring'''






			torch.manual_seed(0			)

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

			a__   		=     PriorTransformer(**__magic_name__			)
			# 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    _UpperCamelCase							(  self :Union[str, Any]			)			->   Dict:

			'''simple docstring'''






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

			a__   		=     CLIPVisionModelWithProjection(__magic_name__			)
			return model


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

			'''simple docstring'''






			a__   		=     CLIPImageProcessor(
			    crop_size=224       ,    do_center_crop=__magic_name__       ,    do_normalize=__magic_name__       ,    do_resize=__magic_name__       ,    image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]       ,    image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]       ,    resample=3       ,    size=224       ,    )

			return image_processor


	def    _UpperCamelCase							(  self :int			)			->   List[str]:

			'''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=1000       ,    clip_sample=__magic_name__       ,    clip_sample_range=10.0       ,    )

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

			return components


	def    _UpperCamelCase							(  self :Optional[int]       ,    __magic_name__ :int       ,    __magic_name__ :List[str]=0			)			->   Dict:

			'''simple docstring'''






			if str(__magic_name__			).startswith('''mps'''			):
					a__   		=     torch.manual_seed(__magic_name__			)
			else:
					a__   		=     torch.Generator(device=__magic_name__			).manual_seed(__magic_name__			)

			a__   		=     floats_tensor((1, 3, 64, 64)       ,    rng=random.Random(__magic_name__			)			).to(__magic_name__			)
			a__   		=     image.cpu().permute(0       ,    2       ,    3       ,    1			)[0]
			a__   		=     Image.fromarray(np.uinta(__magic_name__			)			).convert('''RGB'''			).resize((256, 256)			)

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

			'''simple docstring'''






			a__   		=     '''cpu'''

			a__   		=     self.get_dummy_components()

			a__   		=     self.pipeline_class(**__magic_name__			)
			a__   		=     pipe.to(__magic_name__			)

			pipe.set_progress_bar_config(disable=__magic_name__			)

			a__   		=     pipe(**self.get_dummy_inputs(__magic_name__			)			)
			a__   		=     output.image_embeds

			a__   		=     pipe(
			    **self.get_dummy_inputs(__magic_name__			)       ,    return_dict=__magic_name__       ,    )[0]

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

			assert image.shape == (1, 32)

			a__   		=     np.array(
			    [
			        0.1_071_284,
			        1.3_330_271,
			        0.61_260_223,
			        -0.6_691_065,
			        -0.3_846_852,
			        -1.0_303_661,
			        0.22_716_111,
			        0.03_348_901,
			        0.30_040_675,
			        -0.24_805_029,
			    ]			)

			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]			)			->   Tuple:

			'''simple docstring'''






			a__   		=     torch_device == '''cpu'''
			a__   		=     True
			a__   		=     False

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






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

			'''simple docstring'''






			a__   		=     torch_device == '''cpu'''
			a__   		=     False

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






"""simple docstring"""




import safs
class SCREAMING_SNAKE_CASE       (      safs.SaFileSystem					):






	'''simple docstring'''




