




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  ):
				"""simple docstring"""



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





				@property
				def 				__UpperCAmelCase				( self							:	Tuple				)   ->	Any:
							return 32





				@property
				def 				__UpperCAmelCase				( self							:	int				)   ->	Optional[Any]:
							return 32





				@property
				def 				__UpperCAmelCase				( self							:	Dict				)   ->	List[str]:
							return self.time_input_dim





				@property
				def 				__UpperCAmelCase				( self							:	Optional[int]				)   ->	Union[str, Any]:
							return self.time_input_dim * 4





				@property
				def 				__UpperCAmelCase				( self							:	Tuple				)   ->	Tuple:
							return 1_00





				@property
				def 				__UpperCAmelCase				( self							:	Tuple				)   ->	Dict:
							a       =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"				)
							return tokenizer





				@property
				def 				__UpperCAmelCase				( self							:	Union[str, Any]				)   ->	Optional[Any]:
							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=10_00   , )
							return CLIPTextModelWithProjection(__lowerCamelCase				)





				@property
				def 				__UpperCAmelCase				( self							:	Tuple				)   ->	List[Any]:
							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(**__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 				__UpperCAmelCase				( self							:	Tuple				)   ->	List[Any]:
							torch.manual_seed(0				)
							a       =     CLIPVisionConfig(
							    hidden_size=self.text_embedder_hidden_size   , image_size=2_24   , 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(__lowerCamelCase				)
							return model





				@property
				def 				__UpperCAmelCase				( self							:	Optional[int]				)   ->	str:
							a       =     CLIPImageProcessor(
							    crop_size=2_24   , do_center_crop=__lowerCamelCase   , do_normalize=__lowerCamelCase   , do_resize=__lowerCamelCase   , 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=2_24   , )

							return image_processor





				def 				__UpperCAmelCase				( self							:	str				)   ->	Optional[Any]:
							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=10_00   , clip_sample=__lowerCamelCase   , 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							:	Union[str, Any]   , __lowerCamelCase							:	Dict   , __lowerCamelCase							:	Dict=0				)   ->	Tuple:
							if str(__lowerCamelCase				).startswith("mps"				):
										a       =     torch.manual_seed(__lowerCamelCase				)
							else:
										a       =     torch.Generator(device=__lowerCamelCase				).manual_seed(__lowerCamelCase				)

							a       =     floats_tensor((1, 3, 64, 64)   , 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_56, 2_56)				)

							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							:	Optional[Any]				)   ->	Optional[int]:
							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, -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]				)   ->	Optional[Any]:
							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 				__UpperCAmelCase				( self							:	Dict				)   ->	int:
							a       =     torch_device == "cpu"
							a       =     False

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












import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import SwinaSRImageProcessor
		from transformers.image_transforms import get_image_size




class        snake_case__				(unittest.TestCase  ):
				"""simple docstring"""



				def __init__( self							:	Union[str, Any]   , __lowerCamelCase							:	List[str]   , __lowerCamelCase							:	List[str]=7   , __lowerCamelCase							:	int=3   , __lowerCamelCase							:	Any=18   , __lowerCamelCase							:	Optional[int]=30   , __lowerCamelCase							:	Union[str, Any]=4_00   , __lowerCamelCase							:	Optional[int]=True   , __lowerCamelCase							:	List[str]=1 / 2_55   , __lowerCamelCase							:	Any=True   , __lowerCamelCase							:	Optional[int]=8   , )   ->	Optional[Any]:
							a       =     parent
							a       =     batch_size
							a       =     num_channels
							a       =     image_size
							a       =     min_resolution
							a       =     max_resolution
							a       =     do_rescale
							a       =     rescale_factor
							a       =     do_pad
							a       =     pad_size





				def 				__UpperCAmelCase				( self							:	List[Any]				)   ->	Optional[int]:
							return {
							    "do_rescale": self.do_rescale,
							    "rescale_factor": self.rescale_factor,
							    "do_pad": self.do_pad,
							    "pad_size": self.pad_size,
							}





				def 				__UpperCAmelCase				( self							:	List[Any]   , __lowerCamelCase							:	Optional[int]=False   , __lowerCamelCase							:	Any=False   , __lowerCamelCase							:	List[Any]=False				)   ->	List[Any]:
							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							if equal_resolution:
										a       =     []
										for i in range(self.batch_size				):
													image_inputs.append(
													    np.random.randint(
													        2_55   , size=(self.num_channels, self.max_resolution, self.max_resolution)   , dtype=np.uinta				)				)
							else:
										a       =     []
										for i in range(self.batch_size				):
													a       ,						a       =     np.random.choice(np.arange(self.min_resolution   , self.max_resolution				)   , 2				)
													image_inputs.append(np.random.randint(2_55   , size=(self.num_channels, width, height)   , dtype=np.uinta				)				)

							if not numpify and not torchify:
										# PIL expects the channel dimension as last dimension
										a       =     [Image.fromarray(np.moveaxis(__lowerCamelCase   , 0   , -1				)				) for x in image_inputs]

							if torchify:
										a       =     [torch.from_numpy(__lowerCamelCase				) for x in image_inputs]

							return image_inputs




@require_torch
@require_vision
class        snake_case__				(_UpperCamelCase       ,			unittest.TestCase  ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_			:				Optional[Any]									=   SwinaSRImageProcessor if is_vision_available() else None





				def 				__UpperCAmelCase				( self							:	Dict				)   ->	Tuple:
							a       =     SwinaSRImageProcessingTester(self				)





				@property
				def 				__UpperCAmelCase				( self							:	Optional[Any]				)   ->	List[Any]:
							return self.image_processor_tester.prepare_image_processor_dict()





				def 				__UpperCAmelCase				( self							:	Dict				)   ->	Tuple:
							a       =     self.image_processing_class(**self.image_processor_dict				)
							self.assertTrue(hasattr(__lowerCamelCase   , "do_rescale"				)				)
							self.assertTrue(hasattr(__lowerCamelCase   , "rescale_factor"				)				)
							self.assertTrue(hasattr(__lowerCamelCase   , "do_pad"				)				)
							self.assertTrue(hasattr(__lowerCamelCase   , "pad_size"				)				)





				def 				__UpperCAmelCase				( self							:	Union[str, Any]				)   ->	Union[str, Any]:
							pass





				def 				__UpperCAmelCase				( self							:	int   , __lowerCamelCase							:	int				)   ->	Dict:
							a       ,						a       =     get_image_size(__lowerCamelCase				)
							a       =     self.image_processor_tester.pad_size

							a       =     (old_height // size + 1) * size - old_height
							a       =     (old_width // size + 1) * size - old_width
							return old_height + pad_height, old_width + pad_width





				def 				__UpperCAmelCase				( self							:	Any				)   ->	Dict:
							# Initialize image_processor
							a       =     self.image_processing_class(**self.image_processor_dict				)
							# create random PIL images
							a       =     self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase				)
							for image in image_inputs:
										self.assertIsInstance(__lowerCamelCase   , Image.Image				)

							# Test not batched input
							a       =     image_processor(image_inputs[0]   , return_tensors="pt"				).pixel_values
							a       ,						a       =     self.calculate_expected_size(np.array(image_inputs[0]				)				)
							self.assertEqual(
							    encoded_images.shape   , (
							        1,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )   , )





				def 				__UpperCAmelCase				( self							:	Optional[int]				)   ->	Union[str, Any]:
							# Initialize image_processor
							a       =     self.image_processing_class(**self.image_processor_dict				)
							# create random numpy tensors
							a       =     self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase   , numpify=__lowerCamelCase				)
							for image in image_inputs:
										self.assertIsInstance(__lowerCamelCase   , np.ndarray				)

							# Test not batched input
							a       =     image_processor(image_inputs[0]   , return_tensors="pt"				).pixel_values
							a       ,						a       =     self.calculate_expected_size(image_inputs[0]				)
							self.assertEqual(
							    encoded_images.shape   , (
							        1,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )   , )





				def 				__UpperCAmelCase				( self							:	Optional[Any]				)   ->	int:
							# Initialize image_processor
							a       =     self.image_processing_class(**self.image_processor_dict				)
							# create random PyTorch tensors
							a       =     self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase   , torchify=__lowerCamelCase				)
							for image in image_inputs:
										self.assertIsInstance(__lowerCamelCase   , torch.Tensor				)

							# Test not batched input
							a       =     image_processor(image_inputs[0]   , return_tensors="pt"				).pixel_values
							a       ,						a       =     self.calculate_expected_size(image_inputs[0]				)
							self.assertEqual(
							    encoded_images.shape   , (
							        1,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    )   , )






