




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     A(		UpperCamelCase				, unittest.TestCase  ):



 '''simple docstring'''


 UpperCamelCase		  =		KandinskyVaaControlnetImgaImgPipeline
 UpperCamelCase		  =		['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint''']
 UpperCamelCase		  =		['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint''']
 UpperCamelCase		  =		[
     '''generator''',
     '''height''',
     '''width''',
     '''strength''',
     '''guidance_scale''',
     '''num_inference_steps''',
     '''return_dict''',
     '''guidance_scale''',
     '''num_images_per_prompt''',
     '''output_type''',
     '''return_dict''',
 ]
 UpperCamelCase		  =		False

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

       """simple docstring"""






       return 32

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

       """simple docstring"""






       return 32

 @property
 def 							a__					(							self   :    Tuple    )  ->      List[Any]:

       """simple docstring"""






       return self.time_input_dim

 @property
 def 							a__					(							self   :    Dict    )  ->      str:

       """simple docstring"""






       return self.time_input_dim * 4

 @property
 def 							a__					(							self   :    int    )  ->      List[Any]:

       """simple docstring"""






       return 100

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

       """simple docstring"""






       torch.manual_seed(0    )

       lowerCamelCase_							=       {
           "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,
       }

       lowerCamelCase_							=       UNetaDConditionModel(**snake_case__    )
       return model

 @property
 def 							a__					(							self   :    Tuple    )  ->      Union[str, Any]:

       """simple docstring"""






       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 							a__					(							self   :    Union[str, Any]    )  ->      str:

       """simple docstring"""






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

 def 							a__					(							self   :    Any    )  ->      List[Any]:

       """simple docstring"""






       lowerCamelCase_							=       self.dummy_unet
       lowerCamelCase_							=       self.dummy_movq

       lowerCamelCase_							=       {
           "num_train_timesteps": 1000,
           "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,
       }

       lowerCamelCase_							=       DDIMScheduler(**snake_case__    )

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

       return components

 def 							a__					(							self   :    Union[str, Any]		,				A_   :    List[str]		,				A_   :    int=0    )  ->      List[str]:

       """simple docstring"""






       lowerCamelCase_							=       floats_tensor((1, self.text_embedder_hidden_size)		,				rng=random.Random(snake_case__    )    ).to(snake_case__    )
       lowerCamelCase_							=       floats_tensor((1, self.text_embedder_hidden_size)		,				rng=random.Random(seed + 1    )    ).to(
           snake_case__    )
       # create init_image
       lowerCamelCase_							=       floats_tensor((1, 3, 64, 64)		,				rng=random.Random(snake_case__    )    ).to(snake_case__    )
       lowerCamelCase_							=       image.cpu().permute(0		,				2		,				3		,				1    )[0]
       lowerCamelCase_							=       Image.fromarray(np.uinta(snake_case__    )    ).convert('RGB'    ).resize((256, 256)    )
       # create hint
       lowerCamelCase_							=       floats_tensor((1, 3, 64, 64)		,				rng=random.Random(snake_case__    )    ).to(snake_case__    )

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





 def 							a__					(							self   :    Optional[Any]    )  ->      Tuple:

       """simple docstring"""






       lowerCamelCase_							=       "cpu"

       lowerCamelCase_							=       self.get_dummy_components()

       lowerCamelCase_							=       self.pipeline_class(**snake_case__    )
       lowerCamelCase_							=       pipe.to(snake_case__    )

       pipe.set_progress_bar_config(disable=snake_case__    )

       lowerCamelCase_							=       pipe(**self.get_dummy_inputs(snake_case__    )    )
       lowerCamelCase_							=       output.images

       lowerCamelCase_							=       pipe(
           **self.get_dummy_inputs(snake_case__    )		,				return_dict=snake_case__		,				)[0]

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

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

       lowerCamelCase_							=       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     A(		unittest.TestCase  ):



 '''simple docstring'''


 def 							a__					(							self   :    Any    )  ->      List[Any]:

       """simple docstring"""






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





 def 							a__					(							self   :    Optional[int]    )  ->      Tuple:

       """simple docstring"""






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

       lowerCamelCase_							=       load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'    )
       lowerCamelCase_							=       init_image.resize((512, 512)    )

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

       lowerCamelCase_							=       "A robot, 4k photo"

       lowerCamelCase_							=       KandinskyVaaPriorEmbaEmbPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-2-prior'		,				torch_dtype=torch.floataa    )
       pipe_prior.to(snake_case__    )

       lowerCamelCase_							=       KandinskyVaaControlnetImgaImgPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-2-controlnet-depth'		,				torch_dtype=torch.floataa    )
       lowerCamelCase_							=       pipeline.to(snake_case__    )

       pipeline.set_progress_bar_config(disable=snake_case__    )

       lowerCamelCase_							=       torch.Generator(device='cpu'    ).manual_seed(0    )

       lowerCamelCase_							=       pipe_prior(
           snake_case__		,				image=snake_case__		,				strength=0.85		,				generator=snake_case__		,				negative_prompt=''		,				).to_tuple()

       lowerCamelCase_							=       pipeline(
           image=snake_case__		,				image_embeds=snake_case__		,				negative_image_embeds=snake_case__		,				hint=snake_case__		,				generator=snake_case__		,				num_inference_steps=100		,				height=512		,				width=512		,				strength=0.5		,				output_type='np'		,				)

       lowerCamelCase_							=       output.images[0]

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

       assert_mean_pixel_difference(snake_case__		,				snake_case__    )











"""simple docstring"""



import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


_lowerCAmelCase	:	Union[str, Any]				=      threading.Lock()
_lowerCAmelCase	:	Optional[logging.Handler]				=      None

_lowerCAmelCase	:	Union[str, Any]				=      {
    """debug""": logging.DEBUG,
    """info""": logging.INFO,
    """warning""": logging.WARNING,
    """error""": logging.ERROR,
    """critical""": logging.CRITICAL,
}

_lowerCAmelCase	:	Dict				=      logging.WARNING

_lowerCAmelCase	:	Optional[Any]				=      True


def 	SCREAMING_SNAKE_CASE__       (  )->		List[str]:






     '''simple docstring'''



     UpperCAmelCase__						:    Union[str, Any]							=							os.getenv("TRANSFORMERS_VERBOSITY"			,					snake_case				)
     if env_level_str:
          if env_level_str in log_levels:
               return log_levels[env_level_str]
          else:
               logging.getLogger().warning(
                   f'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '
                   f'has to be one of: { ", ".join(log_levels.keys()				) }'				)
     return _default_log_level


def 	SCREAMING_SNAKE_CASE__       (  )->		str:






     '''simple docstring'''



     return __name__.split("."				)[0]


def 	SCREAMING_SNAKE_CASE__       (  )->		logging.Logger:






     '''simple docstring'''



     return logging.getLogger(_get_library_name()				)


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     global _default_handler

     with _lock:
          if _default_handler:
               # This library has already configured the library root logger.
               return
          UpperCAmelCase__						:    Any							=							logging.StreamHandler()  # Set sys.stderr as stream.
          UpperCAmelCase__						:    Union[str, Any]							=							sys.stderr.flush

          # Apply our default configuration to the library root logger.
          UpperCAmelCase__						:    Union[str, Any]							=							_get_library_root_logger()
          library_root_logger.addHandler(_default_handler				)
          library_root_logger.setLevel(_get_default_logging_level()				)
          UpperCAmelCase__						:    int							=							False


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     global _default_handler

     with _lock:
          if not _default_handler:
               return

          UpperCAmelCase__						:    Union[str, Any]							=							_get_library_root_logger()
          library_root_logger.removeHandler(_default_handler				)
          library_root_logger.setLevel(logging.NOTSET				)
          UpperCAmelCase__						:    Optional[int]							=							None


def 	SCREAMING_SNAKE_CASE__       (  )->		Optional[int]:






     '''simple docstring'''



     return log_levels


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Optional[str] = None				)->		logging.Logger:






     '''simple docstring'''



     if name is None:
          UpperCAmelCase__						:    Tuple							=							_get_library_name()

     _configure_library_root_logger()
     return logging.getLogger(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		int:






     '''simple docstring'''



     _configure_library_root_logger()
     return _get_library_root_logger().getEffectiveLevel()


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : int				)->		None:






     '''simple docstring'''



     _configure_library_root_logger()
     _get_library_root_logger().setLevel(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		Optional[Any]:






     '''simple docstring'''



     return set_verbosity(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		List[str]:






     '''simple docstring'''



     return set_verbosity(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		Tuple:






     '''simple docstring'''



     return set_verbosity(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		str:






     '''simple docstring'''



     return set_verbosity(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     _configure_library_root_logger()

     assert _default_handler is not None
     _get_library_root_logger().removeHandler(_default_handler				)


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     _configure_library_root_logger()

     assert _default_handler is not None
     _get_library_root_logger().addHandler(_default_handler				)


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : logging.Handler				)->		None:






     '''simple docstring'''



     _configure_library_root_logger()

     assert handler is not None
     _get_library_root_logger().addHandler(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : logging.Handler				)->		None:






     '''simple docstring'''



     _configure_library_root_logger()

     assert handler is not None and handler not in _get_library_root_logger().handlers
     _get_library_root_logger().removeHandler(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     _configure_library_root_logger()
     UpperCAmelCase__						:    Dict							=							False


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     _configure_library_root_logger()
     UpperCAmelCase__						:    List[Any]							=							True


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     UpperCAmelCase__						:    Union[str, Any]							=							_get_library_root_logger().handlers

     for handler in handlers:
          UpperCAmelCase__						:    Union[str, Any]							=							logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s"				)
          handler.setFormatter(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  )->		None:






     '''simple docstring'''



     UpperCAmelCase__						:    Any							=							_get_library_root_logger().handlers

     for handler in handlers:
          handler.setFormatter(snake_case				)


def 	SCREAMING_SNAKE_CASE__       (  self       : Optional[int]			,					*snake_case       : List[str]			,					**snake_case       : str				)->		Union[str, Any]:






     '''simple docstring'''



     UpperCAmelCase__						:    Union[str, Any]							=							os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS"			,					snake_case				)
     if no_advisory_warnings:
          return
     self.warning(*snake_case			,					**snake_case				)


_lowerCAmelCase	:	int				=      warning_advice


@functools.lru_cache(snake_case				)
def 	SCREAMING_SNAKE_CASE__       (  self       : Optional[Any]			,					*snake_case       : Dict			,					**snake_case       : Any				)->		Any:






     '''simple docstring'''



     self.warning(*snake_case			,					**snake_case				)


_lowerCAmelCase	:	Tuple				=      warning_once




class 			lowerCAmelCase__			:
   def __init__(		self      :	List[str]							,			*snake_case__      :	Any							,			**snake_case__      :	List[str]							):  # pylint: disable=unused-argument


        '''simple docstring'''
        UpperCAmelCase__						:    List[Any]							=							args[0] if args else None
   def __iter__(		self      :	Any							):


        '''simple docstring'''
        return iter(self._iterator							)
   def __getattr__(		self      :	List[Any]							,			snake_case__      :	Tuple							):


        '''simple docstring'''

        def empty_fn(*snake_case__      :	Dict							,			**snake_case__      :	str							):  # pylint: disable=unused-argument
             return

        return empty_fn
   def __enter__(		self      :	Optional[Any]							):


        '''simple docstring'''
        return self




   def __exit__(		self      :	Tuple							,			snake_case__      :	Tuple							,			snake_case__      :	Any							,			snake_case__      :	Optional[int]							):


        '''simple docstring'''
        return




class 			lowerCAmelCase__			:
   def __call__(		self      :	Optional[Any]							,			*snake_case__      :	Optional[Any]							,			**snake_case__      :	Tuple							):


        '''simple docstring'''
        if _tqdm_active:
             return tqdm_lib.tqdm(*snake_case__							,			**snake_case__							)
        else:
             return EmptyTqdm(*snake_case__							,			**snake_case__							)
   def       __a							(		self      :	Dict							,			*snake_case__      :	List[str]							,			**snake_case__      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							None
        if _tqdm_active:
             return tqdm_lib.tqdm.set_lock(*snake_case__							,			**snake_case__							)




   def       __a							(		self      :	Tuple							):


        '''simple docstring'''
        if _tqdm_active:
             return tqdm_lib.tqdm.get_lock()




_lowerCAmelCase	:	Optional[int]				=      _tqdm_cls()


def 	SCREAMING_SNAKE_CASE__       (  )->		bool:






     '''simple docstring'''



     global _tqdm_active
     return bool(_tqdm_active				)


def 	SCREAMING_SNAKE_CASE__       (  )->		List[Any]:






     '''simple docstring'''



     global _tqdm_active
     UpperCAmelCase__						:    int							=							True
     hf_hub_utils.enable_progress_bars()



def 	SCREAMING_SNAKE_CASE__       (  )->		List[Any]:






     '''simple docstring'''



     global _tqdm_active
     UpperCAmelCase__						:    Optional[Any]							=							False
     hf_hub_utils.disable_progress_bars()


