





'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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 				lowerCAmelCase_						(						__magic_name__  ,unittest.TestCase						):
 __lowerCamelCase  :							Tuple    					=   KandinskyPipeline
 __lowerCamelCase  :							Optional[int]    					=   [
     "prompt",
     "image_embeds",
     "negative_image_embeds",
 ]
 __lowerCamelCase  :							str    					=   ["prompt", "negative_prompt", "image_embeds", "negative_image_embeds"]
 __lowerCamelCase  :							Union[str, Any]    					=   [
     "generator",
     "height",
     "width",
     "latents",
     "guidance_scale",
     "negative_prompt",
     "num_inference_steps",
     "return_dict",
     "guidance_scale",
     "num_images_per_prompt",
     "output_type",
     "return_dict",
 ]
 __lowerCamelCase  :							Tuple    					=   False




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




 @property
 def 							_snake_case				(		self						)      ->							int:
     return 32




 @property
 def 							_snake_case				(		self						)      ->							Optional[Any]:
     return self.time_input_dim




 @property
 def 							_snake_case				(		self						)      ->							List[str]:
     return self.time_input_dim * 4




 @property
 def 							_snake_case				(		self						)      ->							int:
     return 100




 @property
 def 							_snake_case				(		self						)      ->							List[Any]:
     _lowerCAmelCase		     = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"						)
     return tokenizer




 @property
 def 							_snake_case				(		self						)      ->							List[str]:
     torch.manual_seed(0						)
     _lowerCAmelCase		     = 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     ,       )

     _lowerCAmelCase		     = MultilingualCLIP(_lowerCAmelCase						)
     _lowerCAmelCase		     = text_encoder.eval()

     return text_encoder




 @property
 def 							_snake_case				(		self						)      ->							int:
     torch.manual_seed(0						)

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

     _lowerCAmelCase		     = UNetaDConditionModel(**_lowerCAmelCase						)
     return model




 @property
 def 							_snake_case				(		self						)      ->							str:
     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 							_snake_case				(		self						)      ->							Dict:
     torch.manual_seed(0						)
     _lowerCAmelCase		     = VQModel(**self.dummy_movq_kwargs						)
     return model




 def 							_snake_case				(		self						)      ->							Any:
     _lowerCAmelCase		     = self.dummy_text_encoder
     _lowerCAmelCase		     = self.dummy_tokenizer
     _lowerCAmelCase		     = self.dummy_unet
     _lowerCAmelCase		     = self.dummy_movq

     _lowerCAmelCase		     = DDIMScheduler(
         num_train_timesteps=1000     ,       beta_schedule="linear"     ,       beta_start=0.00085     ,       beta_end=0.012     ,       clip_sample=_lowerCAmelCase     ,       set_alpha_to_one=_lowerCAmelCase     ,       steps_offset=1     ,       prediction_type="epsilon"     ,       thresholding=_lowerCAmelCase     ,       )

     _lowerCAmelCase		     = {
         "text_encoder": text_encoder,
         "tokenizer": tokenizer,
         "unet": unet,
         "scheduler": scheduler,
         "movq": movq,
     }
     return components




 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase=0						)      ->							Optional[Any]:
     _lowerCAmelCase		     = floats_tensor((1, self.cross_attention_dim)     ,       rng=random.Random(_lowerCAmelCase						)						).to(_lowerCAmelCase						)
     _lowerCAmelCase		     = floats_tensor((1, self.cross_attention_dim)     ,       rng=random.Random(seed + 1						)						).to(_lowerCAmelCase						)
     if str(_lowerCAmelCase						).startswith("mps"						):
         _lowerCAmelCase		     = torch.manual_seed(_lowerCAmelCase						)
     else:
         _lowerCAmelCase		     = torch.Generator(device=_lowerCAmelCase						).manual_seed(_lowerCAmelCase						)
     _lowerCAmelCase		     = {
         "prompt": "horse",
         "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 							_snake_case				(		self						)      ->							str:
     _lowerCAmelCase		     = "cpu"

     _lowerCAmelCase		     = self.get_dummy_components()

     _lowerCAmelCase		     = self.pipeline_class(**_lowerCAmelCase						)
     _lowerCAmelCase		     = pipe.to(_lowerCAmelCase						)

     pipe.set_progress_bar_config(disable=_lowerCAmelCase						)

     _lowerCAmelCase		     = pipe(**self.get_dummy_inputs(_lowerCAmelCase						)						)
     _lowerCAmelCase		     = output.images

     _lowerCAmelCase		     = pipe(
         **self.get_dummy_inputs(_lowerCAmelCase						)     ,       return_dict=_lowerCAmelCase     ,       )[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.328663, 1.0, 0.23216873, 1.0, 0.92717564, 0.4639046, 0.96894777, 0.31713378, 0.6293953]						)

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




 def 							_snake_case				(		self						)      ->							Dict:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()





 def 							_snake_case				(		self						)      ->							Any:
     _lowerCAmelCase		     = load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/kandinsky/kandinsky_text2img_cat_fp16.npy"						)

     _lowerCAmelCase		     = KandinskyPriorPipeline.from_pretrained(
         "kandinsky-community/kandinsky-2-1-prior"     ,       torch_dtype=torch.floataa						)
     pipe_prior.to(_lowerCAmelCase						)

     _lowerCAmelCase		     = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1"     ,       torch_dtype=torch.floataa						)
     _lowerCAmelCase		     = pipeline.to(_lowerCAmelCase						)
     pipeline.set_progress_bar_config(disable=_lowerCAmelCase						)

     _lowerCAmelCase		     = "red cat, 4k photo"

     _lowerCAmelCase		     = torch.Generator(device="cuda"						).manual_seed(0						)
     _lowerCAmelCase     ,     _lowerCAmelCase		     = pipe_prior(
         _lowerCAmelCase     ,       generator=_lowerCAmelCase     ,       num_inference_steps=5     ,       negative_prompt=""     ,       ).to_tuple()

     _lowerCAmelCase		     = torch.Generator(device="cuda"						).manual_seed(0						)
     _lowerCAmelCase		     = pipeline(
         _lowerCAmelCase     ,       image_embeds=_lowerCAmelCase     ,       negative_image_embeds=_lowerCAmelCase     ,       generator=_lowerCAmelCase     ,       num_inference_steps=100     ,       output_type="np"     ,       )

     _lowerCAmelCase		     = output.images[0]

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

     assert_mean_pixel_difference(_lowerCAmelCase     ,       _lowerCAmelCase						)









'''simple docstring'''


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
       import PIL


_SCREAMING_SNAKE_CASE			=							logging.get_logger(__name__)

class 				lowerCAmelCase_						(						__magic_name__						):
 __lowerCamelCase  :							Optional[int]    					=   ["pixel_values"]




 def __init__(		self     ,       _lowerCAmelCase = True     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = PIL.Image.NEAREST     ,       _lowerCAmelCase = False     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = 1 / 255     ,       _lowerCAmelCase = False     ,       _lowerCAmelCase = True     ,       _lowerCAmelCase = True     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = True     ,       **_lowerCAmelCase     ,       )      ->							None:
     super().__init__(**_lowerCAmelCase						)
     _lowerCAmelCase		     = size if size is not None else {"height": 346, "width": 346}
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase						)
     _lowerCAmelCase		     = crop_size if crop_size is not None else {"height": 289, "width": 289}
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase     ,       param_name="crop_size"						)

     _lowerCAmelCase		     = do_resize
     _lowerCAmelCase		     = size
     _lowerCAmelCase		     = resample
     _lowerCAmelCase		     = do_center_crop
     _lowerCAmelCase		     = crop_size
     _lowerCAmelCase		     = do_rescale
     _lowerCAmelCase		     = rescale_factor
     _lowerCAmelCase		     = rescale_offset
     _lowerCAmelCase		     = do_normalize
     _lowerCAmelCase		     = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     _lowerCAmelCase		     = image_std if image_std is not None else IMAGENET_STANDARD_STD
     _lowerCAmelCase		     = include_top




 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase     ,       _lowerCAmelCase = PIL.Image.NEAREST     ,       _lowerCAmelCase = None     ,       **_lowerCAmelCase     ,       )      ->							np.ndarray:
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase						)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''						)
     return resize(
         _lowerCAmelCase     ,       size=(size["height"], size["width"])     ,       resample=_lowerCAmelCase     ,       data_format=_lowerCAmelCase     ,       **_lowerCAmelCase						)




 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase     ,       _lowerCAmelCase = None     ,       **_lowerCAmelCase     ,       )      ->							np.ndarray:
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase						)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''						)
     return center_crop(_lowerCAmelCase     ,       size=(size["height"], size["width"])     ,       data_format=_lowerCAmelCase     ,       **_lowerCAmelCase						)




 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase     ,       _lowerCAmelCase = True     ,       _lowerCAmelCase = None     ,       **_lowerCAmelCase     ,       )      ->							List[str]:
     if offset:
         _lowerCAmelCase		     = (image - 127.5) * scale
         if data_format is not None:
             _lowerCAmelCase		     = to_channel_dimension_format(_lowerCAmelCase     ,       _lowerCAmelCase						)
         _lowerCAmelCase		     = rescaled_image.astype(np.floataa						)
     else:
         _lowerCAmelCase		     = rescale(_lowerCAmelCase     ,       scale=_lowerCAmelCase     ,       data_format=_lowerCAmelCase     ,       **_lowerCAmelCase						)
     return rescaled_image




 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase     ,       _lowerCAmelCase     ,       _lowerCAmelCase = None     ,       **_lowerCAmelCase     ,       )      ->							np.ndarray:
     return normalize(_lowerCAmelCase     ,       mean=_lowerCAmelCase     ,       std=_lowerCAmelCase     ,       data_format=_lowerCAmelCase     ,       **_lowerCAmelCase						)





 def 							_snake_case				(		self     ,       _lowerCAmelCase     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase=None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = None     ,       _lowerCAmelCase = ChannelDimension.FIRST     ,       **_lowerCAmelCase     ,       )      ->							PIL.Image.Image:
     _lowerCAmelCase		     = do_resize if do_resize is not None else self.do_resize
     _lowerCAmelCase		     = resample if resample is not None else self.resample
     _lowerCAmelCase		     = do_center_crop if do_center_crop is not None else self.do_center_crop
     _lowerCAmelCase		     = do_rescale if do_rescale is not None else self.do_rescale
     _lowerCAmelCase		     = rescale_factor if rescale_factor is not None else self.rescale_factor
     _lowerCAmelCase		     = rescale_offset if rescale_offset is not None else self.rescale_offset
     _lowerCAmelCase		     = do_normalize if do_normalize is not None else self.do_normalize
     _lowerCAmelCase		     = image_mean if image_mean is not None else self.image_mean
     _lowerCAmelCase		     = image_std if image_std is not None else self.image_std
     _lowerCAmelCase		     = include_top if include_top is not None else self.include_top

     _lowerCAmelCase		     = size if size is not None else self.size
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase						)
     _lowerCAmelCase		     = crop_size if crop_size is not None else self.crop_size
     _lowerCAmelCase		     = get_size_dict(_lowerCAmelCase     ,       param_name="crop_size"						)

     _lowerCAmelCase		     = make_list_of_images(_lowerCAmelCase						)

     if not valid_images(_lowerCAmelCase						):
         raise ValueError(
             "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
             "torch.Tensor, tf.Tensor or jax.ndarray."						)

     if do_resize and size is None or resample is None:
         raise ValueError("Size and resample must be specified if do_resize is True."						)

     if do_center_crop and crop_size is None:
         raise ValueError("Crop size must be specified if do_center_crop is True."						)

     if do_rescale and rescale_factor is None:
         raise ValueError("Rescale factor must be specified if do_rescale is True."						)

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError("Image mean and std must be specified if do_normalize is True."						)

     # All transformations expect numpy arrays.
     _lowerCAmelCase		     = [to_numpy_array(_lowerCAmelCase						) for image in images]

     if do_resize:
         _lowerCAmelCase		     = [self.resize(image=_lowerCAmelCase     ,       size=_lowerCAmelCase     ,       resample=_lowerCAmelCase						) for image in images]

     if do_center_crop:
         _lowerCAmelCase		     = [self.center_crop(image=_lowerCAmelCase     ,       size=_lowerCAmelCase						) for image in images]

     if do_rescale:
         _lowerCAmelCase		     = [self.rescale(image=_lowerCAmelCase     ,       scale=_lowerCAmelCase     ,       offset=_lowerCAmelCase						) for image in images]

     if do_normalize:
         _lowerCAmelCase		     = [self.normalize(image=_lowerCAmelCase     ,       mean=_lowerCAmelCase     ,       std=_lowerCAmelCase						) for image in images]

     if include_top:
         _lowerCAmelCase		     = [self.normalize(image=_lowerCAmelCase     ,       mean=[0, 0, 0]     ,       std=_lowerCAmelCase						) for image in images]

     _lowerCAmelCase		     = [to_channel_dimension_format(_lowerCAmelCase     ,       _lowerCAmelCase						) for image in images]

     _lowerCAmelCase		     = {"pixel_values": images}
     return BatchFeature(data=_lowerCAmelCase     ,       tensor_type=_lowerCAmelCase						)


