




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 						_A (  _lowerCamelCase      ,       unittest.TestCase				):
  _UpperCamelCase       :      Optional[int]			=      KandinskyVaaControlnetPipeline
  _UpperCamelCase       :      Union[str, Any]			=      ['''image_embeds''', '''negative_image_embeds''', '''hint''']
  _UpperCamelCase       :      Any			=      ['''image_embeds''', '''negative_image_embeds''', '''hint''']
  _UpperCamelCase       :      Optional[int]			=      [
      '''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  __a      (  self		:     List[Any]				)		->   List[Any]:






       """simple docstring"""







       return 32






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






       """simple docstring"""







       return 32






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






       """simple docstring"""







       return self.time_input_dim






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






       """simple docstring"""







       return self.time_input_dim * 4






  @property
  def  __a      (  self		:     Tuple				)		->   str:






       """simple docstring"""







       return 100






  @property
  def  __a      (  self		:     List[Any]				)		->   Dict:






       """simple docstring"""







       torch.manual_seed(0				)

       lowercase :       Tuple       =			{
           '''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,
       }

       lowercase :       Dict       =			UNetaDConditionModel(**_A				)
       return model






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






       """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		:     List[Any]				)		->   Any:






       """simple docstring"""







       torch.manual_seed(0				)
       lowercase :       Dict       =			VQModel(**self.dummy_movq_kwargs				)
       return model






  def  __a      (  self		:     Tuple				)		->   str:






       """simple docstring"""







       lowercase :       List[str]       =			self.dummy_unet
       lowercase :       Optional[Any]       =			self.dummy_movq

       lowercase :       int       =			DDIMScheduler(
           num_train_timesteps=1_000				,						beta_schedule='''linear'''				,						beta_start=0.00_085				,						beta_end=0.012				,						clip_sample=_A				,						set_alpha_to_one=_A				,						steps_offset=1				,						prediction_type='''epsilon'''				,						thresholding=_A				,						)

       lowercase :       Tuple       =			{
           '''unet''': unet,
           '''scheduler''': scheduler,
           '''movq''': movq,
       }
       return components






  def  __a      (  self		:     Any				,						_A		:     Union[str, Any]				,						_A		:     Optional[int]=0				)		->   List[str]:






       """simple docstring"""







       lowercase :       Tuple       =			floats_tensor((1, self.text_embedder_hidden_size)				,						rng=random.Random(_A				)				).to(_A				)
       lowercase :       int       =			floats_tensor((1, self.text_embedder_hidden_size)				,						rng=random.Random(seed + 1				)				).to(
           _A				)

       # create hint
       lowercase :       Union[str, Any]       =			floats_tensor((1, 3, 64, 64)				,						rng=random.Random(_A				)				).to(_A				)

       if str(_A				).startswith('''mps'''				):
            lowercase :       str       =			torch.manual_seed(_A				)
       else:
            lowercase :       Optional[Any]       =			torch.Generator(device=_A				).manual_seed(_A				)
       lowercase :       Optional[int]       =			{
           '''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  __a      (  self		:     List[str]				)		->   Dict:






       """simple docstring"""







       lowercase :       Dict       =			'''cpu'''

       lowercase :       List[str]       =			self.get_dummy_components()

       lowercase :       Any       =			self.pipeline_class(**_A				)
       lowercase :       int       =			pipe.to(_A				)

       pipe.set_progress_bar_config(disable=_A				)

       lowercase :       str       =			pipe(**self.get_dummy_inputs(_A				)				)
       lowercase :       Tuple       =			output.images

       lowercase :       Dict       =			pipe(
           **self.get_dummy_inputs(_A				)				,						return_dict=_A				,						)[0]

       lowercase :       Optional[int]       =			image[0, -3:, -3:, -1]
       lowercase :       Optional[int]       =			image_from_tuple[0, -3:, -3:, -1]

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

       lowercase :       Any       =			np.array(
           [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595]				)

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






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






       """simple docstring"""







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






  def  __a      (  self		:     int				)		->   List[str]:






       """simple docstring"""







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

       lowercase :       int       =			load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/kandinskyv22/hint_image_cat.png'''				)
       lowercase :       Union[str, Any]       =			torch.from_numpy(np.array(_A				)				).float() / 255.0
       lowercase :       Optional[Any]       =			hint.permute(2				,						0				,						1				).unsqueeze(0				)

       lowercase :       Union[str, Any]       =			KandinskyVaaPriorPipeline.from_pretrained(
           '''kandinsky-community/kandinsky-2-2-prior'''				,						torch_dtype=torch.floataa				)
       pipe_prior.to(_A				)

       lowercase :       Optional[int]       =			KandinskyVaaControlnetPipeline.from_pretrained(
           '''kandinsky-community/kandinsky-2-2-controlnet-depth'''				,						torch_dtype=torch.floataa				)
       lowercase :       Tuple       =			pipeline.to(_A				)
       pipeline.set_progress_bar_config(disable=_A				)

       lowercase :       Optional[int]       =			'''A robot, 4k photo'''

       lowercase :       Tuple       =			torch.Generator(device='''cuda'''				).manual_seed(0				)
       lowercase      ,	lowercase :       Tuple       =			pipe_prior(
           _A				,						generator=_A				,						num_inference_steps=5				,						negative_prompt=''''''				,						).to_tuple()

       lowercase :       int       =			torch.Generator(device='''cuda'''				).manual_seed(0				)
       lowercase :       List[str]       =			pipeline(
           image_embeds=_A				,						negative_image_embeds=_A				,						hint=_A				,						generator=_A				,						num_inference_steps=100				,						output_type='''np'''				,						)

       lowercase :       List[str]       =			output.images[0]

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

       assert_mean_pixel_difference(_A				,						_A				)





class 						_A :  # Public class to implement a graph






  def __init__(  self		:     List[Any]				,						_A		:     int				,						_A		:     int				,						_A		:     list[list[bool]]				)		->   None:






       """simple docstring"""







       lowercase :       Tuple       =			row
       lowercase :       Union[str, Any]       =			col
       lowercase :       int       =			graph






  def  __a      (  self		:     List[Any]				,						_A		:     int				,						_A		:     int				,						_A		:     list[list[bool]]				)		->   bool:






       """simple docstring"""







       return (
           0 <= i < self.ROW
           and 0 <= j < self.COL
           and not visited[i][j]
           and self.graph[i][j]
       )






  def  __a      (  self		:     int				,						_A		:     int				,						_A		:     int				,						_A		:     list[list[bool]]				)		->   None:






       """simple docstring"""







       lowercase :       List[str]       =			[-1, -1, -1, 0, 0, 1, 1, 1]  # Coordinate order
       lowercase :       Dict       =			[-1, 0, 1, -1, 1, -1, 0, 1]
       lowercase :       Dict       =			True  # Make those cells visited
       for k in range(8				):
            if self.is_safe(i + row_nbr[k]				,						j + col_nbr[k]				,						_A				):
                 self.diffs(i + row_nbr[k]				,						j + col_nbr[k]				,						_A				)






  def  __a      (  self		:     List[str]				)		->   int:  # And finally, count all islands.






       """simple docstring"""







       lowercase :       List[str]       =			[[False for j in range(self.COL				)] for i in range(self.ROW				)]
       lowercase :       Optional[Any]       =			0
       for i in range(self.ROW				):
            for j in range(self.COL				):
                 if visited[i][j] is False and self.graph[i][j] == 1:
                      self.diffs(_A				,						_A				,						_A				)
                      count += 1
       return count