





"""simple docstring"""





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 							snake_case							(			__UpperCAmelCase      ,  unittest.TestCase ):

      '''simple docstring'''



      _A     :       str         =       KandinskyVaaControlnetPipeline
      _A     :       Union[str, Any]         =       ['image_embeds', 'negative_image_embeds', 'hint']
      _A     :       Dict         =       ['image_embeds', 'negative_image_embeds', 'hint']
      _A     :       Tuple         =       [
          'generator',
          'height',
          'width',
          'latents',
          'guidance_scale',
          'num_inference_steps',
          'return_dict',
          'guidance_scale',
          'num_images_per_prompt',
          'output_type',
          'return_dict',
      ]
      _A     :       str         =       False

      @property
      def       A_					(							self       :      Dict ):


        '''simple docstring'''




        return 32

      @property
      def       A_					(							self       :      Tuple ):


        '''simple docstring'''




        return 32

      @property
      def       A_					(							self       :      Dict ):


        '''simple docstring'''




        return self.time_input_dim

      @property
      def       A_					(							self       :      Tuple ):


        '''simple docstring'''




        return self.time_input_dim * 4

      @property
      def       A_					(							self       :      int ):


        '''simple docstring'''




        return 100

      @property
      def       A_					(							self       :      Optional[int] ):


        '''simple docstring'''




        torch.manual_seed(0 )

        __UpperCAmelCase    :						List[str]       =						{
            '''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,
        }

        __UpperCAmelCase    :						List[Any]       =						UNetaDConditionModel(**__lowercase )
        return model

      @property
      def       A_					(							self       :      List[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       :      Tuple ):


        '''simple docstring'''




        torch.manual_seed(0 )
        __UpperCAmelCase    :						Tuple       =						VQModel(**self.dummy_movq_kwargs )
        return model

      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




        __UpperCAmelCase    :						Union[str, Any]       =						self.dummy_unet
        __UpperCAmelCase    :						Dict       =						self.dummy_movq

        __UpperCAmelCase    :						Optional[Any]       =						DDIMScheduler(
            num_train_timesteps=1_000						,				beta_schedule='''linear'''						,				beta_start=0.0_0_0_8_5						,				beta_end=0.0_1_2						,				clip_sample=__lowercase						,				set_alpha_to_one=__lowercase						,				steps_offset=1						,				prediction_type='''epsilon'''						,				thresholding=__lowercase						,				)

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

      def       A_					(							self       :      List[str]						,				__lowercase       :      Dict						,				__lowercase       :      Dict=0 ):


        '''simple docstring'''




        __UpperCAmelCase    :						str       =						floats_tensor((1, self.text_embedder_hidden_size)						,				rng=random.Random(__lowercase ) ).to(__lowercase )
        __UpperCAmelCase    :						Any       =						floats_tensor((1, self.text_embedder_hidden_size)						,				rng=random.Random(seed + 1 ) ).to(
            __lowercase )

        # create hint
        __UpperCAmelCase    :						List[str]       =						floats_tensor((1, 3, 64, 64)						,				rng=random.Random(__lowercase ) ).to(__lowercase )

        if str(__lowercase ).startswith('''mps''' ):
          __UpperCAmelCase    :						Any       =						torch.manual_seed(__lowercase )
        else:
          __UpperCAmelCase    :						Union[str, Any]       =						torch.Generator(device=__lowercase ).manual_seed(__lowercase )
        __UpperCAmelCase    :						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       :      str ):


        '''simple docstring'''




        __UpperCAmelCase    :						Union[str, Any]       =						'''cpu'''

        __UpperCAmelCase    :						Dict       =						self.get_dummy_components()

        __UpperCAmelCase    :						Union[str, Any]       =						self.pipeline_class(**__lowercase )
        __UpperCAmelCase    :						int       =						pipe.to(__lowercase )

        pipe.set_progress_bar_config(disable=__lowercase )

        __UpperCAmelCase    :						Optional[Any]       =						pipe(**self.get_dummy_inputs(__lowercase ) )
        __UpperCAmelCase    :						str       =						output.images

        __UpperCAmelCase    :						List[Any]       =						pipe(
            **self.get_dummy_inputs(__lowercase )						,				return_dict=__lowercase						,				)[0]

        __UpperCAmelCase    :						List[Any]       =						image[0, -3:, -3:, -1]
        __UpperCAmelCase    :						Union[str, Any]       =						image_from_tuple[0, -3:, -3:, -1]

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

        __UpperCAmelCase    :						List[str]       =						np.array(
            [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5] )

        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 							snake_case							(			unittest.TestCase ):

      '''simple docstring'''



      def       A_					(							self       :      Dict ):


        '''simple docstring'''




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







      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




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

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

        __UpperCAmelCase    :						Optional[int]       =						KandinskyVaaPriorPipeline.from_pretrained(
            '''kandinsky-community/kandinsky-2-2-prior'''						,				torch_dtype=torch.floataa )
        pipe_prior.to(__lowercase )

        __UpperCAmelCase    :						List[str]       =						KandinskyVaaControlnetPipeline.from_pretrained(
            '''kandinsky-community/kandinsky-2-2-controlnet-depth'''						,				torch_dtype=torch.floataa )
        __UpperCAmelCase    :						str       =						pipeline.to(__lowercase )
        pipeline.set_progress_bar_config(disable=__lowercase )

        __UpperCAmelCase    :						Tuple       =						'''A robot, 4k photo'''

        __UpperCAmelCase    :						List[Any]       =						torch.Generator(device='''cuda''' ).manual_seed(0 )
        __UpperCAmelCase    :						Optional[int]       =						pipe_prior(
            __lowercase						,				generator=__lowercase						,				num_inference_steps=5						,				negative_prompt=''''''						,				).to_tuple()

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

        __UpperCAmelCase    :						Union[str, Any]       =						output.images[0]

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

        assert_mean_pixel_difference(__lowercase						,				__lowercase )






"""simple docstring"""





def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  )						->Tuple:





  """simple docstring"""


  return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_=0  )						->Dict:





  """simple docstring"""


  return sorted(UpperCAmelCase_  ,			key=lambda UpperCAmelCase_  : x[column]  )


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_=float('''inf'''  )  )						->str:





  """simple docstring"""


  for i in range(points_counts - 1  ):
    for j in range(i + 1  ,			UpperCAmelCase_  ):
      __UpperCAmelCase    :						List[Any]       =						euclidean_distance_sqr(points[i]  ,			points[j]  )
      if current_dis < min_dis:
        __UpperCAmelCase    :						Tuple       =						current_dis
  return min_dis


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_=float('''inf'''  )  )						->str:





  """simple docstring"""


  for i in range(min(6  ,			points_counts - 1  )  ,			UpperCAmelCase_  ):
    for j in range(max(0  ,			i - 6  )  ,			UpperCAmelCase_  ):
      __UpperCAmelCase    :						Dict       =						euclidean_distance_sqr(points[i]  ,			points[j]  )
      if current_dis < min_dis:
        __UpperCAmelCase    :						Tuple       =						current_dis
  return min_dis


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  )						->Any:





  """simple docstring"""


  if points_counts <= 3:
    return dis_between_closest_pair(UpperCAmelCase_  ,			UpperCAmelCase_  )

  # recursion
  __UpperCAmelCase    :						Any       =						points_counts // 2
  __UpperCAmelCase    :						Any       =						closest_pair_of_points_sqr(
      UpperCAmelCase_  ,			points_sorted_on_y[:mid]  ,			UpperCAmelCase_  )
  __UpperCAmelCase    :						Tuple       =						closest_pair_of_points_sqr(
      UpperCAmelCase_  ,			points_sorted_on_y[mid:]  ,			points_counts - mid  )
  __UpperCAmelCase    :						List[Any]       =						min(UpperCAmelCase_  ,			UpperCAmelCase_  )
  __UpperCAmelCase    :						int       =						[]
  for point in points_sorted_on_x:
    if abs(point[0] - points_sorted_on_x[mid][0]  ) < closest_pair_dis:
      cross_strip.append(UpperCAmelCase_  )

  __UpperCAmelCase    :						Union[str, Any]       =						dis_between_closest_in_strip(
      UpperCAmelCase_  ,			len(UpperCAmelCase_  )  ,			UpperCAmelCase_  )
  return min(UpperCAmelCase_  ,			UpperCAmelCase_  )


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  )						->List[Any]:





  """simple docstring"""


  __UpperCAmelCase    :						str       =						column_based_sort(UpperCAmelCase_  ,			column=0  )
  __UpperCAmelCase    :						Any       =						column_based_sort(UpperCAmelCase_  ,			column=1  )
  return (
      closest_pair_of_points_sqr(
          UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  )
  ) ** 0.5


if __name__ == "__main__":
  lowercase__				:Optional[Any]				   =       [(2, 3), (1_2, 3_0), (4_0, 5_0), (5, 1), (1_2, 1_0), (3, 4)]
  print('Distance:', closest_pair_of_points(points, len(points)))