

import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    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				( UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							Union[str, Any]										=     KandinskyVaaControlnetPipeline
			_UpperCAmelCase   :							Optional[int]										=     ['''image_embeds''', '''negative_image_embeds''', '''hint''']
			_UpperCAmelCase   :							Optional[Any]										=     ['''image_embeds''', '''negative_image_embeds''', '''hint''']
			_UpperCAmelCase   :							List[str]										=     [
			    '''generator''',
			    '''height''',
			    '''width''',
			    '''latents''',
			    '''guidance_scale''',
			    '''num_inference_steps''',
			    '''return_dict''',
			    '''guidance_scale''',
			    '''num_images_per_prompt''',
			    '''output_type''',
			    '''return_dict''',
			]
			_UpperCAmelCase   :							Optional[int]										=     False



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									return 32



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									return 32



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									return self.time_input_dim



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									return self.time_input_dim * 4



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									return 100



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									torch.manual_seed(0)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       {
									    "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,
									}

									SCREAMING_SNAKE_CASE_: int  		=       UNetaDConditionModel(**lowerCAmelCase__)
									return model



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									return {
									    "block_out_channels": [32, 32, 64, 64],
									    "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": 12,
									    "out_channels": 3,
									    "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
									    "vq_embed_dim": 4,
									}



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									torch.manual_seed(0)
									SCREAMING_SNAKE_CASE_: str  		=       VQModel(**self.dummy_movq_kwargs)
									return model



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.dummy_unet
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.dummy_movq

									SCREAMING_SNAKE_CASE_: Tuple  		=       DDIMScheduler(
									    num_train_timesteps=1000   ,						beta_schedule="linear"   ,						beta_start=0.0_0085   ,						beta_end=0.012   ,						clip_sample=lowerCAmelCase__   ,						set_alpha_to_one=lowerCAmelCase__   ,						steps_offset=1   ,						prediction_type="epsilon"   ,						thresholding=lowerCAmelCase__   ,						)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       {
									    "unet": unet,
									    "scheduler": scheduler,
									    "movq": movq,
									}
									return components



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     List[str]=0):
									SCREAMING_SNAKE_CASE_: List[str]  		=       floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(seed + 1)).to(
									    lowerCAmelCase__)

									# create hint
									SCREAMING_SNAKE_CASE_: int  		=       floats_tensor((1, 3, 64, 64)   ,						rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)

									if str(lowerCAmelCase__).startswith("mps"):
															SCREAMING_SNAKE_CASE_: List[str]  		=       torch.manual_seed(lowerCAmelCase__)
									else:
															SCREAMING_SNAKE_CASE_: List[str]  		=       torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       {
									    "image_embeds": image_embeds,
									    "negative_image_embeds": negative_image_embeds,
									    "hint": hint,
									    "generator": generator,
									    "height": 64,
									    "width": 64,
									    "guidance_scale": 4.0,
									    "num_inference_steps": 2,
									    "output_type": "np",
									}
									return inputs




			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Any  		=       "cpu"

									SCREAMING_SNAKE_CASE_: Dict  		=       self.get_dummy_components()

									SCREAMING_SNAKE_CASE_: Any  		=       self.pipeline_class(**lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       pipe.to(lowerCAmelCase__)

									pipe.set_progress_bar_config(disable=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: List[str]  		=       pipe(**self.get_dummy_inputs(lowerCAmelCase__))
									SCREAMING_SNAKE_CASE_: List[str]  		=       output.images

									SCREAMING_SNAKE_CASE_: Tuple  		=       pipe(
									    **self.get_dummy_inputs(lowerCAmelCase__)   ,						return_dict=lowerCAmelCase__   ,						)[0]

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       image[0, -3:, -3:, -1]
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       image_from_tuple[0, -3:, -3:, -1]

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

									SCREAMING_SNAKE_CASE_: Any  		=       np.array(
									    [0.695_9826, 0.86_8279, 0.755_8092, 0.6876_9467, 0.8580_5804, 0.6597_7496, 0.4488_5302, 0.595_9111, 0.425_1595])

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




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()




			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       load_numpy(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									    "/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy")

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

									SCREAMING_SNAKE_CASE_: Tuple  		=       KandinskyVaaPriorPipeline.from_pretrained(
									    "kandinsky-community/kandinsky-2-2-prior"   ,						torch_dtype=torch.floataa)
									pipe_prior.to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       KandinskyVaaControlnetPipeline.from_pretrained(
									    "kandinsky-community/kandinsky-2-2-controlnet-depth"   ,						torch_dtype=torch.floataa)
									SCREAMING_SNAKE_CASE_: Dict  		=       pipeline.to(lowerCAmelCase__)
									pipeline.set_progress_bar_config(disable=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Dict  		=       "A robot, 4k photo"

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.Generator(device="cuda").manual_seed(0)
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Dict  		=       pipe_prior(
									    lowerCAmelCase__   ,						generator=lowerCAmelCase__   ,						num_inference_steps=5   ,						negative_prompt=""   ,						).to_tuple()

									SCREAMING_SNAKE_CASE_: int  		=       torch.Generator(device="cuda").manual_seed(0)
									SCREAMING_SNAKE_CASE_: Any  		=       pipeline(
									    image_embeds=lowerCAmelCase__   ,						negative_image_embeds=lowerCAmelCase__   ,						hint=lowerCAmelCase__   ,						generator=lowerCAmelCase__   ,						num_inference_steps=100   ,						output_type="np"   ,						)

									SCREAMING_SNAKE_CASE_: int  		=       output.images[0]

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

									assert_mean_pixel_difference(lowerCAmelCase__   ,						lowerCAmelCase__)









import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
						import torch

						from transformers.generation import DisjunctiveConstraint



@require_torch
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									# For consistency across different places the DisjunctiveConstraint is called,
									# dc.token_ids is a list of integers. It is also initialized only by integers.

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       [[1, 2, 4], [1, 2, 3, 4]]
									SCREAMING_SNAKE_CASE_: Any  		=       DisjunctiveConstraint(lowerCAmelCase__)
									self.assertTrue(isinstance(dc.token_ids   ,						lowerCAmelCase__))

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]))

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint([torch.LongTensor([1, 2, 4]), torch.LongTensor([1, 2, 3, 4, 5])])



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									# We can't have constraints that are complete subsets of another. This leads to a preverse
									# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
									# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
									# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
									# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       [[1, 2], [1, 2, 3, 4]]

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint(lowerCAmelCase__)  # fails here



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       [[1, 2, 3], [1, 2, 4]]

									SCREAMING_SNAKE_CASE_: Tuple  		=       DisjunctiveConstraint(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       dc.update(1)
									SCREAMING_SNAKE_CASE_: Dict  		=       stepped is True and completed is False and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: str  		=       dc.update(2)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       stepped is True and completed is False and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(3)
									SCREAMING_SNAKE_CASE_: Tuple  		=       stepped is True and completed is True and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.current_seq == [1, 2, 3])




			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

									SCREAMING_SNAKE_CASE_: List[Any]  		=       DisjunctiveConstraint(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       dc.update(1)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Dict  		=       dc.update(2)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(4)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2, 4])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       dc.update(5)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.current_seq == [1, 2, 4, 5])

									dc.reset()

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[Any]  		=       dc.update(1)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.remaining() == 3)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(2)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.remaining() == 2)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       dc.update(5)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.remaining() == 0)
									self.assertTrue(dc.current_seq == [1, 2, 5])






