


'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, 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	(       _SCREAMING_SNAKE_CASE     ,unittest.TestCase):







    """simple docstring"""



    lowercase       			= KandinskyVaaPipeline
    lowercase       			= [
        'image_embeds',
        'negative_image_embeds',
    ]
    lowercase       			= ['image_embeds', 'negative_image_embeds']
    lowercase       			= [
        'generator',
        'height',
        'width',
        'latents',
        'guidance_scale',
        'num_inference_steps',
        'return_dict',
        'guidance_scale',
        'num_images_per_prompt',
        'output_type',
        'return_dict',
    ]
    lowercase       			= False

    @property
    def __lowercase       (       self   :  Any		)       ->  Tuple:
      return 32

    @property
    def __lowercase       (       self   :  Any		)       ->  Any:
      return 32

    @property
    def __lowercase       (       self   :  Union[str, Any]		)       ->  str:
      return self.time_input_dim

    @property
    def __lowercase       (       self   :  Optional[int]		)       ->  Dict:
      return self.time_input_dim * 4

    @property
    def __lowercase       (       self   :  Optional[Any]		)       ->  List[Any]:
      return 1_00

    @property
    def __lowercase       (       self   :  List[Any]		)       ->  Union[str, Any]:
      torch.manual_seed(0		)

      lowerCAmelCase_      :				Optional[int]      =       {
          """in_channels""": 4,
          # Out channels is double in channels because predicts mean and variance
          """out_channels""": 8,
          """addition_embed_type""": """image""",
          """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_      :				Optional[int]      =       UNetaDConditionModel(**lowerCamelCase		)
      return model

    @property
    def __lowercase       (       self   :  Tuple		)       ->  Optional[int]:
      return {
          "block_out_channels": [32, 64],
          "down_block_types": ["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",
          ],
          "vq_embed_dim": 4,
      }

    @property
    def __lowercase       (       self   :  Dict		)       ->  Any:
      torch.manual_seed(0		)
      lowerCAmelCase_      :				str      =       VQModel(**self.dummy_movq_kwargs		)
      return model

    def __lowercase       (       self   :  Any		)       ->  List[str]:
      lowerCAmelCase_      :				int      =       self.dummy_unet
      lowerCAmelCase_      :				Union[str, Any]      =       self.dummy_movq

      lowerCAmelCase_      :				Optional[Any]      =       DDIMScheduler(
          num_train_timesteps=10_00   ,						beta_schedule="""linear"""   ,						beta_start=0.00_085   ,						beta_end=0.012   ,						clip_sample=lowerCamelCase   ,						set_alpha_to_one=lowerCamelCase   ,						steps_offset=1   ,						prediction_type="""epsilon"""   ,						thresholding=lowerCamelCase   ,						)

      lowerCAmelCase_      :				List[Any]      =       {
          """unet""": unet,
          """scheduler""": scheduler,
          """movq""": movq,
      }
      return components

    def __lowercase       (       self   :  Optional[int]   ,						lowerCamelCase   :  Optional[int]   ,						lowerCamelCase   :  Union[str, Any]=0		)       ->  Any:
      lowerCAmelCase_      :				Any      =       floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(lowerCamelCase		)		).to(lowerCamelCase		)
      lowerCAmelCase_      :				Optional[int]      =       floats_tensor((1, self.text_embedder_hidden_size)   ,						rng=random.Random(seed + 1		)		).to(
          lowerCamelCase		)
      if str(lowerCamelCase		).startswith("""mps"""		):
        lowerCAmelCase_      :				List[Any]      =       torch.manual_seed(lowerCamelCase		)
      else:
        lowerCAmelCase_      :				Any      =       torch.Generator(device=lowerCamelCase		).manual_seed(lowerCamelCase		)
      lowerCAmelCase_      :				str      =       {
          """image_embeds""": image_embeds,
          """negative_image_embeds""": negative_image_embeds,
          """generator""": generator,
          """height""": 64,
          """width""": 64,
          """guidance_scale""": 4.0,
          """num_inference_steps""": 2,
          """output_type""": """np""",
      }
      return inputs





    def __lowercase       (       self   :  Tuple		)       ->  Optional[Any]:
      lowerCAmelCase_      :				Optional[int]      =       """cpu"""

      lowerCAmelCase_      :				Optional[Any]      =       self.get_dummy_components()

      lowerCAmelCase_      :				List[Any]      =       self.pipeline_class(**lowerCamelCase		)
      lowerCAmelCase_      :				Optional[int]      =       pipe.to(lowerCamelCase		)

      pipe.set_progress_bar_config(disable=lowerCamelCase		)

      lowerCAmelCase_      :				Union[str, Any]      =       pipe(**self.get_dummy_inputs(lowerCamelCase		)		)
      lowerCAmelCase_      :				Dict      =       output.images

      lowerCAmelCase_      :				Dict      =       pipe(
          **self.get_dummy_inputs(lowerCamelCase		)   ,						return_dict=lowerCamelCase   ,						)[0]

      lowerCAmelCase_      :				List[str]      =       image[0, -3:, -3:, -1]
      lowerCAmelCase_      :				str      =       image_from_tuple[0, -3:, -3:, -1]

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

      lowerCAmelCase_      :				Dict      =       np.array(
          [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046]		)

      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 __lowercase       (       self   :  int		)       ->  str:
      # clean up the VRAM after each test
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





    def __lowercase       (       self   :  Union[str, Any]		)       ->  List[Any]:
      lowerCAmelCase_      :				int      =       load_numpy(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
          """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"""		)

      lowerCAmelCase_      :				str      =       KandinskyVaaPriorPipeline.from_pretrained(
          """kandinsky-community/kandinsky-2-2-prior"""   ,						torch_dtype=torch.floataa		)
      pipe_prior.to(lowerCamelCase		)

      lowerCAmelCase_      :				Any      =       KandinskyVaaPipeline.from_pretrained(
          """kandinsky-community/kandinsky-2-2-decoder"""   ,						torch_dtype=torch.floataa		)
      lowerCAmelCase_      :				Optional[Any]      =       pipeline.to(lowerCamelCase		)
      pipeline.set_progress_bar_config(disable=lowerCamelCase		)

      lowerCAmelCase_      :				List[str]      =       """red cat, 4k photo"""

      lowerCAmelCase_      :				Optional[Any]      =       torch.Generator(device="""cuda"""		).manual_seed(0		)
      lowerCAmelCase_,							lowerCAmelCase_      :				int      =       pipe_prior(
          lowerCamelCase   ,						generator=lowerCamelCase   ,						num_inference_steps=5   ,						negative_prompt=""""""   ,						).to_tuple()

      lowerCAmelCase_      :				str      =       torch.Generator(device="""cuda"""		).manual_seed(0		)
      lowerCAmelCase_      :				Tuple      =       pipeline(
          image_embeds=lowerCamelCase   ,						negative_image_embeds=lowerCamelCase   ,						generator=lowerCamelCase   ,						num_inference_steps=1_00   ,						output_type="""np"""   ,						)

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

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

      assert_mean_pixel_difference(lowerCamelCase   ,						lowerCamelCase		)







'''simple docstring'''






from pathlib import Path

import cva
import numpy as np
from matplotlib import pyplot as plt







def     UpperCamelCase_      (   A__ :       np.ndarray							,   A__ :       np.ndarray							,   A__ :       np.ndarray							,   A__ :       int							,   A__ :       int ):
  '''simple docstring'''





  lowerCAmelCase_      :				List[Any]      =       cva.getAffineTransform(A__							,   A__ )
  return cva.warpAffine(A__							,   A__							,   (rows, cols) )


if __name__ == "__main__":
  # read original image
  __A :  Dict    							=				cva.imread(
      str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg")
  )
  # turn image in gray scale value
  __A :  List[Any]    							=				cva.cvtColor(image, cva.COLOR_BGR2GRAY)
  # get image shape
  __A							,			__A :  Dict    							=				gray_img.shape

  # set different points to rotate image
  __A :  List[str]    							=				np.array([[50, 50], [200, 50], [50, 200]], np.floataa)
  __A :  Tuple    							=				np.array([[10, 100], [200, 50], [100, 250]], np.floataa)
  __A :  List[Any]    							=				np.array([[50, 50], [150, 50], [120, 200]], np.floataa)
  __A :  Optional[Any]    							=				np.array([[10, 100], [80, 50], [180, 250]], np.floataa)

  # add all rotated images in a list
  __A :  Optional[Any]    							=				[
      gray_img,
      get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
      get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
      get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
  ]

  # plot different image rotations
  __A :  Dict    							=				plt.figure(1)
  __A :  Optional[Any]    							=				["Original", "Rotation 1", "Rotation 2", "Rotation 3"]
  for i, image in enumerate(images):
    plt.subplot(2, 2, i + 1), plt.imshow(image, "gray")
    plt.title(titles[i])
    plt.axis("off")
    plt.subplots_adjust(left=0.0, bottom=0.0_5, right=1.0, top=0.9_5)
  plt.show()



