


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetImgaImgPipeline,
    KandinskyVaaPriorEmbaEmbPipeline,
    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      UpperCamelCase(	_a  ,				unittest.TestCase ):
					snake_case_		:					int    					=						KandinskyVaaControlnetImgaImgPipeline
					snake_case_		:					Dict    					=						["""image_embeds""", """negative_image_embeds""", """image""", """hint"""]
					snake_case_		:					Union[str, Any]    					=						["""image_embeds""", """negative_image_embeds""", """image""", """hint"""]
					snake_case_		:					Tuple    					=						[
					    """generator""",
					    """height""",
					    """width""",
					    """strength""",
					    """guidance_scale""",
					    """num_inference_steps""",
					    """return_dict""",
					    """guidance_scale""",
					    """num_images_per_prompt""",
					    """output_type""",
					    """return_dict""",
					]
					snake_case_		:					int    					=						False


					@property
					def 				SCREAMING_SNAKE_CASE_	(    self						:		Dict    )      ->						Union[str, Any]:




											'''simple docstring'''

											return 3_2


					@property
					def 				SCREAMING_SNAKE_CASE_	(    self						:		Dict    )      ->						int:




											'''simple docstring'''

											return 3_2


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




											'''simple docstring'''

											return self.time_input_dim


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




											'''simple docstring'''

											return self.time_input_dim * 4


					@property
					def 				SCREAMING_SNAKE_CASE_	(    self						:		Tuple    )      ->						Dict:




											'''simple docstring'''

											return 1_0_0


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




											'''simple docstring'''

											torch.manual_seed(0    )

											__snake_case				=		{
											    "in_channels": 8,
											    # Out channels is double in channels because predicts mean and variance
											    "out_channels": 8,
											    "addition_embed_type": "image_hint",
											    "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,
											}

											__snake_case				=		UNetaDConditionModel(**SCREAMING_SNAKE_CASE    )
											return model


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




											'''simple docstring'''

											return {
											    "block_out_channels": [3_2, 3_2, 6_4, 6_4],
											    "down_block_types": [
											        "DownEncoderBlock2D",
											        "DownEncoderBlock2D",
											        "DownEncoderBlock2D",
											        "AttnDownEncoderBlock2D",
											    ],
											    "in_channels": 3,
											    "latent_channels": 4,
											    "layers_per_block": 1,
											    "norm_num_groups": 8,
											    "norm_type": "spatial",
											    "num_vq_embeddings": 1_2,
											    "out_channels": 3,
											    "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
											    "vq_embed_dim": 4,
											}


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




											'''simple docstring'''

											torch.manual_seed(0    )
											__snake_case				=		VQModel(**self.dummy_movq_kwargs    )
											return model


					def 				SCREAMING_SNAKE_CASE_	(    self						:		List[str]    )      ->						List[str]:




											'''simple docstring'''

											__snake_case				=		self.dummy_unet
											__snake_case				=		self.dummy_movq

											__snake_case				=		{
											    "num_train_timesteps": 1_0_0_0,
											    "beta_schedule": "linear",
											    "beta_start": 0.00085,
											    "beta_end": 0.012,
											    "clip_sample": False,
											    "set_alpha_to_one": False,
											    "steps_offset": 0,
											    "prediction_type": "epsilon",
											    "thresholding": False,
											}

											__snake_case				=		DDIMScheduler(**SCREAMING_SNAKE_CASE    )

											__snake_case				=		{
											    "unet": unet,
											    "scheduler": scheduler,
											    "movq": movq,
											}

											return components


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[Any]  ,     SCREAMING_SNAKE_CASE						:		List[Any]  ,     SCREAMING_SNAKE_CASE						:		int=0    )      ->						Any:




											'''simple docstring'''

											__snake_case				=		floats_tensor((1, self.text_embedder_hidden_size)  ,     rng=random.Random(SCREAMING_SNAKE_CASE    )    ).to(SCREAMING_SNAKE_CASE    )
											__snake_case				=		floats_tensor((1, self.text_embedder_hidden_size)  ,     rng=random.Random(seed + 1    )    ).to(
											    SCREAMING_SNAKE_CASE    )
											# create init_image
											__snake_case				=		floats_tensor((1, 3, 6_4, 6_4)  ,     rng=random.Random(SCREAMING_SNAKE_CASE    )    ).to(SCREAMING_SNAKE_CASE    )
											__snake_case				=		image.cpu().permute(0  ,     2  ,     3  ,     1    )[0]
											__snake_case				=		Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE    )    ).convert("RGB"    ).resize((2_5_6, 2_5_6)    )
											# create hint
											__snake_case				=		floats_tensor((1, 3, 6_4, 6_4)  ,     rng=random.Random(SCREAMING_SNAKE_CASE    )    ).to(SCREAMING_SNAKE_CASE    )

											if str(SCREAMING_SNAKE_CASE    ).startswith("mps"    ):
																	__snake_case				=		torch.manual_seed(SCREAMING_SNAKE_CASE    )
											else:
																	__snake_case				=		torch.Generator(device=SCREAMING_SNAKE_CASE    ).manual_seed(SCREAMING_SNAKE_CASE    )
											__snake_case				=		{
											    "image": init_image,
											    "image_embeds": image_embeds,
											    "negative_image_embeds": negative_image_embeds,
											    "hint": hint,
											    "generator": generator,
											    "height": 6_4,
											    "width": 6_4,
											    "num_inference_steps": 1_0,
											    "guidance_scale": 7.0,
											    "strength": 0.2,
											    "output_type": "np",
											}
											return inputs






					def 				SCREAMING_SNAKE_CASE_	(    self						:		Union[str, Any]    )      ->						Dict:




											'''simple docstring'''

											__snake_case				=		"cpu"

											__snake_case				=		self.get_dummy_components()

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

											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE    )

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

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

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

											assert image.shape == (1, 6_4, 6_4, 3)

											__snake_case				=		np.array(
											    [0.54985034, 0.55509365, 0.52561504, 0.5570494, 0.5593818, 0.5263979, 0.50285643, 0.5069846, 0.51196736]    )
											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      UpperCamelCase(	unittest.TestCase ):


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[int]    )      ->						Union[str, Any]:




											'''simple docstring'''

											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






					def 				SCREAMING_SNAKE_CASE_	(    self						:		str    )      ->						List[str]:




											'''simple docstring'''

											__snake_case				=		load_numpy(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy"    )

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"    )
											__snake_case				=		init_image.resize((5_1_2, 5_1_2)    )

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/kandinskyv22/hint_image_cat.png"    )
											__snake_case				=		torch.from_numpy(np.array(SCREAMING_SNAKE_CASE    )    ).float() / 255.0
											__snake_case				=		hint.permute(2  ,     0  ,     1    ).unsqueeze(0    )

											__snake_case				=		"A robot, 4k photo"

											__snake_case				=		KandinskyVaaPriorEmbaEmbPipeline.from_pretrained(
											    "kandinsky-community/kandinsky-2-2-prior"  ,     torch_dtype=torch.floataa    )
											pipe_prior.to(SCREAMING_SNAKE_CASE    )

											__snake_case				=		KandinskyVaaControlnetImgaImgPipeline.from_pretrained(
											    "kandinsky-community/kandinsky-2-2-controlnet-depth"  ,     torch_dtype=torch.floataa    )
											__snake_case				=		pipeline.to(SCREAMING_SNAKE_CASE    )

											pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE    )

											__snake_case				=		torch.Generator(device="cpu"    ).manual_seed(0    )

											__snake_case		,       __snake_case				=		pipe_prior(
											    SCREAMING_SNAKE_CASE  ,     image=SCREAMING_SNAKE_CASE  ,     strength=0.85  ,     generator=SCREAMING_SNAKE_CASE  ,     negative_prompt=""  ,     ).to_tuple()

											__snake_case				=		pipeline(
											    image=SCREAMING_SNAKE_CASE  ,     image_embeds=SCREAMING_SNAKE_CASE  ,     negative_image_embeds=SCREAMING_SNAKE_CASE  ,     hint=SCREAMING_SNAKE_CASE  ,     generator=SCREAMING_SNAKE_CASE  ,     num_inference_steps=1_0_0  ,     height=5_1_2  ,     width=5_1_2  ,     strength=0.5  ,     output_type="np"  ,     )

											__snake_case				=		output.images[0]

											assert image.shape == (5_1_2, 5_1_2, 3)

											assert_mean_pixel_difference(SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE    )









from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching





def 						_lowerCAmelCase							(     )    ->						Tuple:


						'''simple docstring'''






						import os as original_os
						from os import path as original_path
						from os import rename as original_rename
						from os.path import dirname as original_dirname
						from os.path import join as original_join

						assert _test_patching.os is original_os
						assert _test_patching.path is original_path
						assert _test_patching.join is original_join

						assert _test_patching.renamed_os is original_os
						assert _test_patching.renamed_path is original_path
						assert _test_patching.renamed_join is original_join

						__snake_case				=		"__test_patch_submodule_mock__"
						with patch_submodule(_test_patching   ,						"os.path.join"   ,						_lowerCAmelCase			):
												# Every way to access os.path.join must be patched, and the rest must stay untouched

												# check os.path.join
												assert isinstance(_test_patching.os   ,						_PatchedModuleObj			)
												assert isinstance(_test_patching.os.path   ,						_PatchedModuleObj			)
												assert _test_patching.os.path.join is mock

												# check path.join
												assert isinstance(_test_patching.path   ,						_PatchedModuleObj			)
												assert _test_patching.path.join is mock

												# check join
												assert _test_patching.join is mock

												# check that the other attributes are untouched
												assert _test_patching.os.rename is original_rename
												assert _test_patching.path.dirname is original_dirname
												assert _test_patching.os.path.dirname is original_dirname

												# Even renamed modules or objects must be patched

												# check renamed_os.path.join
												assert isinstance(_test_patching.renamed_os   ,						_PatchedModuleObj			)
												assert isinstance(_test_patching.renamed_os.path   ,						_PatchedModuleObj			)
												assert _test_patching.renamed_os.path.join is mock

												# check renamed_path.join
												assert isinstance(_test_patching.renamed_path   ,						_PatchedModuleObj			)
												assert _test_patching.renamed_path.join is mock

												# check renamed_join
												assert _test_patching.renamed_join is mock

												# check that the other attributes are untouched
												assert _test_patching.renamed_os.rename is original_rename
												assert _test_patching.renamed_path.dirname is original_dirname
												assert _test_patching.renamed_os.path.dirname is original_dirname

						# check that everthing is back to normal when the patch is over

						assert _test_patching.os is original_os
						assert _test_patching.path is original_path
						assert _test_patching.join is original_join

						assert _test_patching.renamed_os is original_os
						assert _test_patching.renamed_path is original_path
						assert _test_patching.renamed_join is original_join





def 						_lowerCAmelCase							(     )    ->						int:


						'''simple docstring'''






						assert _test_patching.open is open

						__snake_case				=		"__test_patch_submodule_builtin_mock__"
						# _test_patching has "open" in its globals
						assert _test_patching.open is open
						with patch_submodule(_test_patching   ,						"open"   ,						_lowerCAmelCase			):
												assert _test_patching.open is mock

						# check that everthing is back to normal when the patch is over

						assert _test_patching.open is open





def 						_lowerCAmelCase							(     )    ->						Optional[Any]:


						'''simple docstring'''






						__snake_case				=		"__test_patch_submodule_missing_mock__"
						with patch_submodule(_test_patching   ,						"pandas.read_csv"   ,						_lowerCAmelCase			):
												pass





def 						_lowerCAmelCase							(     )    ->						Optional[Any]:


						'''simple docstring'''






						__snake_case				=		"__test_patch_submodule_missing_builtin_mock__"
						# _test_patching doesn't have "len" in its globals
						assert getattr(_test_patching   ,						"len"   ,						_lowerCAmelCase			) is None
						with patch_submodule(_test_patching   ,						"len"   ,						_lowerCAmelCase			):
												assert _test_patching.len is mock
						assert _test_patching.len is len





def 						_lowerCAmelCase							(     )    ->						Optional[Any]:


						'''simple docstring'''






						__snake_case				=		"__test_patch_submodule_start_and_stop_mock__"
						__snake_case				=		patch_submodule(_test_patching   ,						"open"   ,						_lowerCAmelCase			)
						assert _test_patching.open is open
						patch.start()
						assert _test_patching.open is mock
						patch.stop()
						assert _test_patching.open is open





def 						_lowerCAmelCase							(     )    ->						Any:


						'''simple docstring'''






						from os import rename as original_rename
						from os.path import dirname as original_dirname
						from os.path import join as original_join

						__snake_case				=		"__test_patch_submodule_successive_join__"
						__snake_case				=		"__test_patch_submodule_successive_dirname__"
						__snake_case				=		"__test_patch_submodule_successive_rename__"
						assert _test_patching.os.path.join is original_join
						assert _test_patching.os.path.dirname is original_dirname
						assert _test_patching.os.rename is original_rename

						with patch_submodule(_test_patching   ,						"os.path.join"   ,						_lowerCAmelCase			):
												with patch_submodule(_test_patching   ,						"os.rename"   ,						_lowerCAmelCase			):
																		with patch_submodule(_test_patching   ,						"os.path.dirname"   ,						_lowerCAmelCase			):
																								assert _test_patching.os.path.join is mock_join
																								assert _test_patching.os.path.dirname is mock_dirname
																								assert _test_patching.os.rename is mock_rename

    # try another order
						with patch_submodule(_test_patching   ,						"os.rename"   ,						_lowerCAmelCase			):
												with patch_submodule(_test_patching   ,						"os.path.join"   ,						_lowerCAmelCase			):
																		with patch_submodule(_test_patching   ,						"os.path.dirname"   ,						_lowerCAmelCase			):
																								assert _test_patching.os.path.join is mock_join
																								assert _test_patching.os.path.dirname is mock_dirname
																								assert _test_patching.os.rename is mock_rename

						assert _test_patching.os.path.join is original_join
						assert _test_patching.os.path.dirname is original_dirname
						assert _test_patching.os.rename is original_rename





def 						_lowerCAmelCase							(     )    ->						str:


						'''simple docstring'''






						__snake_case				=		"__test_patch_submodule_doesnt_exist_mock__"
						with patch_submodule(_test_patching   ,						"__module_that_doesn_exist__.__attribute_that_doesn_exist__"   ,						_lowerCAmelCase			):
												pass
						with patch_submodule(_test_patching   ,						"os.__attribute_that_doesn_exist__"   ,						_lowerCAmelCase			):
												pass





