

import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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			):
						_lowercase        =     KandinskyImgaImgPipeline
						_lowercase        =     ["prompt", "image_embeds", "negative_image_embeds", "image"]
						_lowercase        =     [
						    "prompt",
						    "negative_prompt",
						    "image_embeds",
						    "negative_image_embeds",
						    "image",
						]
						_lowercase        =     [
						    "generator",
						    "height",
						    "width",
						    "strength",
						    "guidance_scale",
						    "negative_prompt",
						    "num_inference_steps",
						    "return_dict",
						    "guidance_scale",
						    "num_images_per_prompt",
						    "output_type",
						    "return_dict",
						]
						_lowercase        =     False


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return 32


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return 32


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return self.time_input_dim


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return self.time_input_dim * 4


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return 100


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"		)
										return tokenizer


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										torch.manual_seed(0		)
										_UpperCAmelCase    :						Dict							=      MCLIPConfig(
										    numDims=self.cross_attention_dim  ,   transformerDimensions=self.text_embedder_hidden_size  ,   hidden_size=self.text_embedder_hidden_size  ,   intermediate_size=37  ,   num_attention_heads=4  ,   num_hidden_layers=5  ,   vocab_size=1005  ,   )

										_UpperCAmelCase    :						List[str]							=      MultilingualCLIP(A_		)
										_UpperCAmelCase    :						int							=      text_encoder.eval()

										return text_encoder


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										torch.manual_seed(0		)

										_UpperCAmelCase    :						Dict							=      {
										    "in_channels": 4,
										    # Out channels is double in channels because predicts mean and variance
										    "out_channels": 8,
										    "addition_embed_type": "text_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": "text_image_proj",
										    "cross_attention_dim": self.cross_attention_dim,
										    "attention_head_dim": 4,
										    "resnet_time_scale_shift": "scale_shift",
										    "class_embed_type": None,
										}

										_UpperCAmelCase    :						Union[str, Any]							=      UNetaDConditionModel(**A_		)
										return model


						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										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     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										torch.manual_seed(0		)
										_UpperCAmelCase    :						List[str]							=      VQModel(**self.dummy_movq_kwargs		)
										return model


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      self.dummy_text_encoder
										_UpperCAmelCase    :						int							=      self.dummy_tokenizer
										_UpperCAmelCase    :						Tuple							=      self.dummy_unet
										_UpperCAmelCase    :						Any							=      self.dummy_movq

										_UpperCAmelCase    :						List[str]							=      {
										    "num_train_timesteps": 1000,
										    "beta_schedule": "linear",
										    "beta_start": 0.0_00_85,
										    "beta_end": 0.0_12,
										    "clip_sample": False,
										    "set_alpha_to_one": False,
										    "steps_offset": 0,
										    "prediction_type": "epsilon",
										    "thresholding": False,
										}

										_UpperCAmelCase    :						List[str]							=      DDIMScheduler(**A_		)

										_UpperCAmelCase    :						int							=      {
										    "text_encoder": text_encoder,
										    "tokenizer": tokenizer,
										    "unet": unet,
										    "scheduler": scheduler,
										    "movq": movq,
										}

										return components


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_=0		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      floats_tensor((1, self.cross_attention_dim)  ,   rng=random.Random(A_		)		).to(A_		)
										_UpperCAmelCase    :						Optional[Any]							=      floats_tensor((1, self.cross_attention_dim)  ,   rng=random.Random(seed + 1		)		).to(A_		)
										# create init_image
										_UpperCAmelCase    :						Optional[int]							=      floats_tensor((1, 3, 64, 64)  ,   rng=random.Random(A_		)		).to(A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      image.cpu().permute(0  ,   2  ,   3  ,   1		)[0]
										_UpperCAmelCase    :						int							=      Image.fromarray(np.uinta(A_		)		).convert("RGB"		).resize((256, 256)		)

										if str(A_		).startswith("mps"		):
														_UpperCAmelCase    :						str							=      torch.manual_seed(A_		)
										else:
														_UpperCAmelCase    :						List[Any]							=      torch.Generator(device=A_		).manual_seed(A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      {
										    "prompt": "horse",
										    "image": init_image,
										    "image_embeds": image_embeds,
										    "negative_image_embeds": negative_image_embeds,
										    "generator": generator,
										    "height": 64,
										    "width": 64,
										    "num_inference_steps": 10,
										    "guidance_scale": 7.0,
										    "strength": 0.2,
										    "output_type": "np",
										}
										return inputs





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      "cpu"

										_UpperCAmelCase    :						int							=      self.get_dummy_components()

										_UpperCAmelCase    :						Dict							=      self.pipeline_class(**A_		)
										_UpperCAmelCase    :						str							=      pipe.to(A_		)

										pipe.set_progress_bar_config(disable=A_		)

										_UpperCAmelCase    :						Tuple							=      pipe(**self.get_dummy_inputs(A_		)		)
										_UpperCAmelCase    :						int							=      output.images

										_UpperCAmelCase    :						List[str]							=      pipe(
										    **self.get_dummy_inputs(A_		)  ,   return_dict=A_  ,   )[0]

										_UpperCAmelCase    :						Any							=      image[0, -3:, -3:, -1]
										_UpperCAmelCase    :						Optional[Any]							=      image_from_tuple[0, -3:, -3:, -1]

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

										_UpperCAmelCase    :						Optional[Any]							=      np.array(
										    [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33]		)
										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     _UpperCAmelCase			(    self		):







										'''simple docstring'''


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





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
										    "/kandinsky/kandinsky_img2img_frog.npy"		)

										_UpperCAmelCase    :						str							=      load_image(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"		)
										_UpperCAmelCase    :						Tuple							=      "A red cartoon frog, 4k"

										_UpperCAmelCase    :						Optional[int]							=      KandinskyPriorPipeline.from_pretrained(
										    "kandinsky-community/kandinsky-2-1-prior"  ,   torch_dtype=torch.floataa		)
										pipe_prior.to(A_		)

										_UpperCAmelCase    :						int							=      KandinskyImgaImgPipeline.from_pretrained(
										    "kandinsky-community/kandinsky-2-1"  ,   torch_dtype=torch.floataa		)
										_UpperCAmelCase    :						Union[str, Any]							=      pipeline.to(A_		)

										pipeline.set_progress_bar_config(disable=A_		)

										_UpperCAmelCase    :						Tuple							=      torch.Generator(device="cpu"		).manual_seed(0		)
										_UpperCAmelCase						,							_UpperCAmelCase    :						Any							=      pipe_prior(
										    A_  ,   generator=A_  ,   num_inference_steps=5  ,   negative_prompt=""  ,   ).to_tuple()

										_UpperCAmelCase    :						List[Any]							=      pipeline(
										    A_  ,   image=A_  ,   image_embeds=A_  ,   negative_image_embeds=A_  ,   generator=A_  ,   num_inference_steps=100  ,   height=768  ,   width=768  ,   strength=0.2  ,   output_type="np"  ,   )

										_UpperCAmelCase    :						List[Any]							=      output.images[0]

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

										assert_mean_pixel_difference(A_  ,   A_		)





from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload

class 			a					:


						def __init__(    self  ,   A_ = None		):







										'''simple docstring'''


										if components is None:
														_UpperCAmelCase    :						Dict							=      []
										_UpperCAmelCase    :						Dict							=      list(A_		)


						def __len__(    self		):







										'''simple docstring'''


										return len(self.__components		)


						def __str__(    self		):







										'''simple docstring'''


										return "(" + ",".join(map(A_  ,   self.__components		)		) + ")"


						def __add__(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      len(self		)
										if size == len(A_		):
														_UpperCAmelCase    :						Union[str, Any]							=      [self.__components[i] + other.component(A_		) for i in range(A_		)]
														return Vector(A_		)
										else:
														raise Exception("must have the same size"		)


						def __sub__(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[str]							=      len(self		)
										if size == len(A_		):
														_UpperCAmelCase    :						Optional[Any]							=      [self.__components[i] - other.component(A_		) for i in range(A_		)]
														return Vector(A_		)
										else:  # error case
														raise Exception("must have the same size"		)


						@overload
						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										...


						@overload
						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										...


						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   (float, int)		):
														_UpperCAmelCase    :						str							=      [c * other for c in self.__components]
														return Vector(A_		)
										elif isinstance(A_  ,   A_		) and len(self		) == len(A_		):
														_UpperCAmelCase    :						int							=      len(self		)
														_UpperCAmelCase    :						Any							=      [self.__components[i] * other.component(A_		) for i in range(A_		)]
														return sum(A_		)
										else:  # error case
														raise Exception("invalid operand!"		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return Vector(self.__components		)


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		) and -len(self.__components		) <= i < len(self.__components		):
														return self.__components[i]
										else:
														raise Exception("index out of range"		)


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										assert -len(self.__components		) <= pos < len(self.__components		)
										_UpperCAmelCase    :						Any							=      value


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										if len(self.__components		) == 0:
														raise Exception("Vector is empty"		)
										_UpperCAmelCase    :						Dict							=      [c**2 for c in self.__components]
										return math.sqrt(sum(A_		)		)





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = False		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      self * other
										_UpperCAmelCase    :						str							=      self.euclidean_length() * other.euclidean_length()
										if deg:
														return math.degrees(math.acos(num / den		)		)
										else:
														return math.acos(num / den		)







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int	)				->    Vector:
				assert isinstance(lowerCAmelCase					, lowerCAmelCase	)
				return Vector([0] * dimension	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int					, lowerCAmelCase:					int	)				->    Vector:
				assert isinstance(lowerCAmelCase					, lowerCAmelCase	) and (isinstance(lowerCAmelCase					, lowerCAmelCase	))
				_UpperCAmelCase    :						Tuple							=      [0] * dimension
				_UpperCAmelCase    :						Optional[Any]							=      1
				return Vector(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					float					, lowerCAmelCase:					Vector					, lowerCAmelCase:					Vector	)				->    Vector:
				assert (
				    isinstance(lowerCAmelCase					, lowerCAmelCase	)
				    and isinstance(lowerCAmelCase					, lowerCAmelCase	)
				    and (isinstance(lowerCAmelCase					, (int, float)	))
				)
				return x * scalar + y

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int					, lowerCAmelCase:					int					, lowerCAmelCase:					int	)				->    Vector:
				random.seed(lowerCAmelCase	)
				_UpperCAmelCase    :						Optional[int]							=      [random.randint(lowerCAmelCase					, lowerCAmelCase	) for _ in range(lowerCAmelCase	)]
				return Vector(lowerCAmelCase	)

class 			a					:


						def __init__(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      matrix
										_UpperCAmelCase    :						Union[str, Any]							=      w
										_UpperCAmelCase    :						str							=      h


						def __str__(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      ""
										for i in range(self.__height		):
														ans += "|"
														for j in range(self.__width		):
																		if j < self.__width - 1:
																						ans += str(self.__matrix[i][j]		) + ","
																		else:
																						ans += str(self.__matrix[i][j]		) + "|\n"
										return ans


						def __add__(    self  ,   A_		):







										'''simple docstring'''


										if self.__width == other.width() and self.__height == other.height():
														_UpperCAmelCase    :						Optional[int]							=      []
														for i in range(self.__height		):
																		_UpperCAmelCase    :						List[str]							=      [
																		    self.__matrix[i][j] + other.component(A_  ,   A_		)
																		    for j in range(self.__width		)
																		]
																		matrix.append(A_		)
														return Matrix(A_  ,   self.__width  ,   self.__height		)
										else:
														raise Exception("matrix must have the same dimension!"		)


						def __sub__(    self  ,   A_		):







										'''simple docstring'''


										if self.__width == other.width() and self.__height == other.height():
														_UpperCAmelCase    :						Optional[Any]							=      []
														for i in range(self.__height		):
																		_UpperCAmelCase    :						Tuple							=      [
																		    self.__matrix[i][j] - other.component(A_  ,   A_		)
																		    for j in range(self.__width		)
																		]
																		matrix.append(A_		)
														return Matrix(A_  ,   self.__width  ,   self.__height		)
										else:
														raise Exception("matrices must have the same dimension!"		)


						@overload
						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										...


						@overload
						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										...


						def __mul__(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		):  # matrix-vector
														if len(A_		) == self.__width:
																		_UpperCAmelCase    :						Union[str, Any]							=      zero_vector(self.__height		)
																		for i in range(self.__height		):
																						_UpperCAmelCase    :						List[Any]							=      [
																						    self.__matrix[i][j] * other.component(A_		)
																						    for j in range(self.__width		)
																						]
																						ans.change_component(A_  ,   sum(A_		)		)
																		return ans
														else:
																		raise Exception(
																		    "vector must have the same size as the "
																		    "number of columns of the matrix!"		)
										elif isinstance(A_  ,   (int, float)		):  # matrix-scalar
														_UpperCAmelCase    :						Any							=      [
														    [self.__matrix[i][j] * other for j in range(self.__width		)]
														    for i in range(self.__height		)
														]
														return Matrix(A_  ,   self.__width  ,   self.__height		)
										return None


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return self.__height


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return self.__width


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										if 0 <= x < self.__height and 0 <= y < self.__width:
														return self.__matrix[x][y]
										else:
														raise Exception("change_component: indices out of bounds"		)


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										if 0 <= x < self.__height and 0 <= y < self.__width:
														_UpperCAmelCase    :						Tuple							=      value
										else:
														raise Exception("change_component: indices out of bounds"		)


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										if self.__height != self.__width:
														raise Exception("Matrix is not square"		)
										_UpperCAmelCase    :						Union[str, Any]							=      self.__matrix[:x] + self.__matrix[x + 1 :]
										for i in range(len(A_		)		):
														_UpperCAmelCase    :						Tuple							=      minor[i][:y] + minor[i][y + 1 :]
										return Matrix(A_  ,   self.__width - 1  ,   self.__height - 1		).determinant()


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										if self.__height != self.__width:
														raise Exception("Matrix is not square"		)
										if 0 <= x < self.__height and 0 <= y < self.__width:
														return (-1) ** (x + y) * self.minor(A_  ,   A_		)
										else:
														raise Exception("Indices out of bounds"		)





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										if self.__height != self.__width:
														raise Exception("Matrix is not square"		)
										if self.__height < 1:
														raise Exception("Matrix has no element"		)
										elif self.__height == 1:
														return self.__matrix[0][0]
										elif self.__height == 2:
														return (
														    self.__matrix[0][0] * self.__matrix[1][1]
														    - self.__matrix[0][1] * self.__matrix[1][0]
														)
										else:
														_UpperCAmelCase    :						Dict							=      [
														    self.__matrix[0][y] * self.cofactor(0  ,   A_		) for y in range(self.__width		)
														]
														return sum(A_		)







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int	)				->    Matrix:
				_UpperCAmelCase    :						list[list[float]]							=      [[0] * n for _ in range(lowerCAmelCase	)]
				return Matrix(lowerCAmelCase					, lowerCAmelCase					, lowerCAmelCase	)





def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int					, lowerCAmelCase:					int					, lowerCAmelCase:					int					, lowerCAmelCase:					int	)				->    Matrix:
				random.seed(lowerCAmelCase	)
				_UpperCAmelCase    :						list[list[float]]							=      [
				    [random.randint(lowerCAmelCase					, lowerCAmelCase	) for _ in range(lowerCAmelCase	)] for _ in range(lowerCAmelCase	)
				]
				return Matrix(lowerCAmelCase					, lowerCAmelCase					, lowerCAmelCase	)


