
import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()


class     lowercase (		lowerCamelCase_  ,       unittest.TestCase       ):
		__lowercase	:	Any     					=    KandinskyVaaImgaImgPipeline
		__lowercase	:	List[Any]     					=    ['''image_embeds''', '''negative_image_embeds''', '''image''']
		__lowercase	:	Any     					=    [
		    '''image_embeds''',
		    '''negative_image_embeds''',
		    '''image''',
		]
		__lowercase	:	Union[str, Any]     					=    [
		    '''generator''',
		    '''height''',
		    '''width''',
		    '''strength''',
		    '''guidance_scale''',
		    '''num_inference_steps''',
		    '''return_dict''',
		    '''guidance_scale''',
		    '''num_images_per_prompt''',
		    '''output_type''',
		    '''return_dict''',
		]
		__lowercase	:	int     					=    False



		@property
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				return 32



		@property
		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				return 32



		@property
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				return self.time_input_dim



		@property
		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				return self.time_input_dim * 4



		@property
		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				return 100



		@property
		def __UpperCamelCase			(			self	)  -> Tuple:
				"""simple docstring"""
				torch.manual_seed(0	)

				UpperCamelCase          =					{
				    'in_channels': 4,
				    # Out channels is double in channels because predicts mean and variance
				    'out_channels': 8,
				    'addition_embed_type': 'image',
				    'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
				    'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
				    'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
				    'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
				    'layers_per_block': 1,
				    'encoder_hid_dim': self.text_embedder_hidden_size,
				    'encoder_hid_dim_type': 'image_proj',
				    'cross_attention_dim': self.cross_attention_dim,
				    'attention_head_dim': 4,
				    'resnet_time_scale_shift': 'scale_shift',
				    'class_embed_type': None,
				}

				UpperCamelCase          =					UNetaDConditionModel(**__snake_case	)
				return model



		@property
		def __UpperCamelCase			(			self	)  -> List[Any]:
				"""simple docstring"""
				return {
				    "block_out_channels": [32, 64],
				    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
				    "in_channels": 3,
				    "latent_channels": 4,
				    "layers_per_block": 1,
				    "norm_num_groups": 8,
				    "norm_type": "spatial",
				    "num_vq_embeddings": 12,
				    "out_channels": 3,
				    "up_block_types": [
				        "AttnUpDecoderBlock2D",
				        "UpDecoderBlock2D",
				    ],
				    "vq_embed_dim": 4,
				}



		@property
		def __UpperCamelCase			(			self	)  -> Optional[Any]:
				"""simple docstring"""
				torch.manual_seed(0	)
				UpperCamelCase          =					VQModel(**self.dummy_movq_kwargs	)
				return model



		def __UpperCamelCase			(			self	)  -> Dict:
				"""simple docstring"""
				UpperCamelCase          =					self.dummy_unet
				UpperCamelCase          =					self.dummy_movq

				UpperCamelCase          =					{
				    'num_train_timesteps': 1_000,
				    'beta_schedule': 'linear',
				    'beta_start': 0.0_0085,
				    'beta_end': 0.012,
				    'clip_sample': False,
				    'set_alpha_to_one': False,
				    'steps_offset': 0,
				    'prediction_type': 'epsilon',
				    'thresholding': False,
				}

				UpperCamelCase          =					DDIMScheduler(**__snake_case	)

				UpperCamelCase          =					{
				    'unet': unet,
				    'scheduler': scheduler,
				    'movq': movq,
				}

				return components



		def __UpperCamelCase			(			self    ,				A_    ,				A_=0	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					floats_tensor((1, self.text_embedder_hidden_size)    ,				rng=random.Random(__snake_case	)	).to(__snake_case	)
				UpperCamelCase          =					floats_tensor((1, self.text_embedder_hidden_size)    ,				rng=random.Random(seed + 1	)	).to(
				    __snake_case	)
				# create init_image
				UpperCamelCase          =					floats_tensor((1, 3, 64, 64)    ,				rng=random.Random(__snake_case	)	).to(__snake_case	)
				UpperCamelCase          =					image.cpu().permute(0    ,				2    ,				3    ,				1	)[0]
				UpperCamelCase          =					Image.fromarray(np.uinta(__snake_case	)	).convert('RGB'	).resize((256, 256)	)

				if str(__snake_case	).startswith('mps'	):
						UpperCamelCase          =					torch.manual_seed(__snake_case	)
				else:
						UpperCamelCase          =					torch.Generator(device=__snake_case	).manual_seed(__snake_case	)
				UpperCamelCase          =					{
				    'image': init_image,
				    'image_embeds': image_embeds,
				    'negative_image_embeds': negative_image_embeds,
				    'generator': generator,
				    'height': 64,
				    'width': 64,
				    'num_inference_steps': 10,
				    'guidance_scale': 7.0,
				    'strength': 0.2,
				    'output_type': 'np',
				}
				return inputs



		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				UpperCamelCase          =					'cpu'

				UpperCamelCase          =					self.get_dummy_components()

				UpperCamelCase          =					self.pipeline_class(**__snake_case	)
				UpperCamelCase          =					pipe.to(__snake_case	)

				pipe.set_progress_bar_config(disable=__snake_case	)

				UpperCamelCase          =					pipe(**self.get_dummy_inputs(__snake_case	)	)
				UpperCamelCase          =					output.images

				UpperCamelCase          =					pipe(
				    **self.get_dummy_inputs(__snake_case	)    ,				return_dict=__snake_case    ,				)[0]

				UpperCamelCase          =					image[0, -3:, -3:, -1]
				UpperCamelCase          =					image_from_tuple[0, -3:, -3:, -1]

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

				UpperCamelCase          =					np.array(
				    [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263]	)
				assert (
				    np.abs(image_slice.flatten() - expected_slice	).max() < 1e-2
				), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
				assert (
				    np.abs(image_from_tuple_slice.flatten() - expected_slice	).max() < 1e-2
				), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''






@slow
@require_torch_gpu
class     lowercase (		unittest.TestCase       ):



		def __UpperCamelCase			(			self	)  -> List[str]:
				"""simple docstring"""
				# clean up the VRAM after each test
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()



		def __UpperCamelCase			(			self	)  -> Dict:
				"""simple docstring"""
				UpperCamelCase          =					load_numpy(
				    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
				    '/kandinskyv22/kandinskyv22_img2img_frog.npy'	)

				UpperCamelCase          =					load_image(
				    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'	)
				UpperCamelCase          =					'A red cartoon frog, 4k'

				UpperCamelCase          =					KandinskyVaaPriorPipeline.from_pretrained(
				    'kandinsky-community/kandinsky-2-2-prior'    ,				torch_dtype=torch.floataa	)
				pipe_prior.to(__snake_case	)

				UpperCamelCase          =					KandinskyVaaImgaImgPipeline.from_pretrained(
				    'kandinsky-community/kandinsky-2-2-decoder'    ,				torch_dtype=torch.floataa	)
				UpperCamelCase          =					pipeline.to(__snake_case	)

				pipeline.set_progress_bar_config(disable=__snake_case	)

				UpperCamelCase          =					torch.Generator(device='cpu'	).manual_seed(0	)
				UpperCamelCase     ,  UpperCamelCase          =					pipe_prior(
				    __snake_case    ,				generator=__snake_case    ,				num_inference_steps=5    ,				negative_prompt=''    ,				).to_tuple()

				UpperCamelCase          =					pipeline(
				    image=__snake_case    ,				image_embeds=__snake_case    ,				negative_image_embeds=__snake_case    ,				generator=__snake_case    ,				num_inference_steps=100    ,				height=768    ,				width=768    ,				strength=0.2    ,				output_type='np'    ,				)

				UpperCamelCase          =					output.images[0]

				assert image.shape == (768, 768, 3)

				assert_mean_pixel_difference(__snake_case    ,				__snake_case	)


import os
import sys
import unittest


_UpperCAmelCase :			str              =	os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
_UpperCAmelCase :			Tuple              =	os.path.join(git_repo_path, "src", "diffusers")


class     lowercase (		unittest.TestCase       ):



		def __UpperCamelCase			(			self	)  -> Tuple:
				"""simple docstring"""
				UpperCamelCase          =					find_backend('    if not is_torch_available():'	)
				self.assertEqual(A_    ,				'torch'	)

				# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
				# self.assertEqual(backend_with_underscore, "tensorflow_text")

				UpperCamelCase          =					find_backend('    if not (is_torch_available() and is_transformers_available()):'	)
				self.assertEqual(A_    ,				'torch_and_transformers'	)

				# double_backend_with_underscore = find_backend(
				#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
				# )
				# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

				UpperCamelCase          =					find_backend(
				    '    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'	)
				self.assertEqual(A_    ,				'torch_and_transformers_and_onnx'	)



		def __UpperCamelCase			(			self	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					read_init()
				# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
				self.assertIn('torch'    ,				A_	)
				self.assertIn('torch_and_transformers'    ,				A_	)
				self.assertIn('flax_and_transformers'    ,				A_	)
				self.assertIn('torch_and_transformers_and_onnx'    ,				A_	)

				# Likewise, we can't assert on the exact content of a key
				self.assertIn('UNet2DModel'    ,				objects['torch']	)
				self.assertIn('FlaxUNet2DConditionModel'    ,				objects['flax']	)
				self.assertIn('StableDiffusionPipeline'    ,				objects['torch_and_transformers']	)
				self.assertIn('FlaxStableDiffusionPipeline'    ,				objects['flax_and_transformers']	)
				self.assertIn('LMSDiscreteScheduler'    ,				objects['torch_and_scipy']	)
				self.assertIn('OnnxStableDiffusionPipeline'    ,				objects['torch_and_transformers_and_onnx']	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					create_dummy_object('CONSTANT'    ,				'\'torch\''	)
				self.assertEqual(A_    ,				'\nCONSTANT = None\n'	)

				UpperCamelCase          =					create_dummy_object('function'    ,				'\'torch\''	)
				self.assertEqual(
				    A_    ,				'\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'	)

				UpperCamelCase          =					'\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n'
				UpperCamelCase          =					create_dummy_object('FakeClass'    ,				'\'torch\''	)
				self.assertEqual(A_    ,				A_	)



		def __UpperCamelCase			(			self	)  -> List[str]:
				"""simple docstring"""
				UpperCamelCase          =					'# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n'
				UpperCamelCase          =					create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}	)
				self.assertEqual(dummy_files['torch']    ,				A_	)
