"""simple docstring"""







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        UpperCamelCase		(			lowercase_						,      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			)	->      int:


        '''simple docstring'''


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


        '''simple docstring'''


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


        '''simple docstring'''


        return self.time_input_dim
   @property
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        return self.time_input_dim * 4
   @property
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        return 100
   @property
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				str													=	XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base'			)
        return tokenizer
   @property
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        torch.manual_seed(0			)
        lowercase_	:				Optional[int]													=	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     ,)

        lowercase_	:				Optional[int]													=	MultilingualCLIP(__UpperCamelCase			)
        lowercase_	:				Dict													=	text_encoder.eval()

        return text_encoder
   @property
   def 			_UpperCAmelCase   (			self			)	->      Optional[int]:


        '''simple docstring'''


        torch.manual_seed(0			)

        lowercase_	:				Optional[Any]													=	{
            '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,
        }

        lowercase_	:				int													=	UNetaDConditionModel(**__UpperCamelCase			)
        return model
   @property
   def 			_UpperCAmelCase   (			self			)	->      int:


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


        '''simple docstring'''


        torch.manual_seed(0			)
        lowercase_	:				Union[str, Any]													=	VQModel(**self.dummy_movq_kwargs			)
        return model
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Tuple													=	self.dummy_text_encoder
        lowercase_	:				Dict													=	self.dummy_tokenizer
        lowercase_	:				Optional[int]													=	self.dummy_unet
        lowercase_	:				int													=	self.dummy_movq

        lowercase_	:				str													=	{
            'num_train_timesteps': 1000,
            'beta_schedule': 'linear',
            'beta_start': 0.0_0085,
            'beta_end': 0.012,
            'clip_sample': False,
            'set_alpha_to_one': False,
            'steps_offset': 0,
            'prediction_type': 'epsilon',
            'thresholding': False,
        }

        lowercase_	:				Optional[int]													=	DDIMScheduler(**__UpperCamelCase			)

        lowercase_	:				Tuple													=	{
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'unet': unet,
            'scheduler': scheduler,
            'movq': movq,
        }

        return components
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase=0			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Dict													=	floats_tensor((1, self.cross_attention_dim)     ,rng=random.Random(__UpperCamelCase			)			).to(__UpperCamelCase			)
        lowercase_	:				str													=	floats_tensor((1, self.cross_attention_dim)     ,rng=random.Random(seed + 1			)			).to(__UpperCamelCase			)
        # create init_image
        lowercase_	:				List[str]													=	floats_tensor((1, 3, 64, 64)     ,rng=random.Random(__UpperCamelCase			)			).to(__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	image.cpu().permute(0     ,2     ,3     ,1			)[0]
        lowercase_	:				Optional[Any]													=	Image.fromarray(np.uinta(__UpperCamelCase			)			).convert('RGB'			).resize((256, 256)			)

        if str(__UpperCamelCase			).startswith('mps'			):
             lowercase_	:				int													=	torch.manual_seed(__UpperCamelCase			)
        else:
             lowercase_	:				int													=	torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
        lowercase_	:				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			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	'cpu'

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

        lowercase_	:				Tuple													=	self.pipeline_class(**__UpperCamelCase			)
        lowercase_	:				Dict													=	pipe.to(__UpperCamelCase			)

        pipe.set_progress_bar_config(disable=__UpperCamelCase			)

        lowercase_	:				Dict													=	pipe(**self.get_dummy_inputs(__UpperCamelCase			)			)
        lowercase_	:				str													=	output.images

        lowercase_	:				Optional[int]													=	pipe(
            **self.get_dummy_inputs(__UpperCamelCase			)     ,return_dict=__UpperCamelCase     ,)[0]

        lowercase_	:				int													=	image[0, -3:, -3:, -1]
        lowercase_	:				Union[str, Any]													=	image_from_tuple[0, -3:, -3:, -1]

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

        lowercase_	:				Tuple													=	np.array(
            [0.6147_4943, 0.607_3539, 0.4330_8544, 0.592_8269, 0.4749_3595, 0.4675_5973, 0.461_3838, 0.4536_8797, 0.5011_9233]			)
        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        UpperCamelCase		(			unittest.TestCase  ):
   def 			_UpperCAmelCase   (			self			)	->      Dict:


        '''simple docstring'''


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







   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Any													=	load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/kandinsky/kandinsky_img2img_frog.npy'			)

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

        lowercase_	:				Dict													=	KandinskyPriorPipeline.from_pretrained(
            'kandinsky-community/kandinsky-2-1-prior'     ,torch_dtype=torch.floataa			)
        pipe_prior.to(__UpperCamelCase			)

        lowercase_	:				str													=	KandinskyImgaImgPipeline.from_pretrained(
            'kandinsky-community/kandinsky-2-1'     ,torch_dtype=torch.floataa			)
        lowercase_	:				str													=	pipeline.to(__UpperCamelCase			)

        pipeline.set_progress_bar_config(disable=__UpperCamelCase			)

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

        lowercase_	:				int													=	pipeline(
            __UpperCamelCase     ,image=__UpperCamelCase     ,image_embeds=__UpperCamelCase     ,negative_image_embeds=__UpperCamelCase     ,generator=__UpperCamelCase     ,num_inference_steps=100     ,height=768     ,width=768     ,strength=0.2     ,output_type='np'     ,)

        lowercase_	:				Dict													=	output.images[0]

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

        assert_mean_pixel_difference(__UpperCamelCase     ,__UpperCamelCase			)


"""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,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_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        UpperCamelCase		(			lowercase_  ):
   lowercase							=  ['pixel_values']
   def __init__(			self     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = 0.9     ,__UpperCamelCase = PILImageResampling.BICUBIC     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = 1 / 255     ,__UpperCamelCase = True     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      None:


        '''simple docstring'''


        super().__init__(**__UpperCamelCase			)
        lowercase_	:				Optional[int]													=	size if size is not None else {'shortest_edge': 224}
        lowercase_	:				Union[str, Any]													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	crop_size if crop_size is not None else {'height': 224, 'width': 224}
        lowercase_	:				Optional[int]													=	get_size_dict(__UpperCamelCase     ,param_name='crop_size'			)

        lowercase_	:				List[str]													=	do_resize
        lowercase_	:				List[Any]													=	size
        lowercase_	:				int													=	crop_pct
        lowercase_	:				Dict													=	resample
        lowercase_	:				List[str]													=	do_center_crop
        lowercase_	:				Union[str, Any]													=	crop_size
        lowercase_	:				List[Any]													=	do_rescale
        lowercase_	:				Tuple													=	rescale_factor
        lowercase_	:				Tuple													=	do_normalize
        lowercase_	:				Union[str, Any]													=	image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        lowercase_	:				int													=	image_std if image_std is not None else IMAGENET_DEFAULT_STD
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = PILImageResampling.BICUBIC     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        lowercase_	:				Any													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        if "shortest_edge" not in size and ("height" not in size or "width" not in size):
             raise ValueError(f'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''			)
        if crop_pct is not None:
             if "shortest_edge" in size:
                  lowercase_	:				Union[str, Any]													=	int(size['shortest_edge'] / crop_pct			)
             elif "height" in size and "width" in size:
                  if size["height"] == size["width"]:
                       lowercase_	:				Tuple													=	int(size['height'] / crop_pct			)
                  else:
                       lowercase_	:				Dict													=	(int(size['height'] / crop_pct			), int(size['width'] / crop_pct			))
             else:
                  raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase			)			)

             lowercase_	:				int													=	get_resize_output_image_size(__UpperCamelCase     ,size=__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        else:
             if "shortest_edge" in size:
                  lowercase_	:				Optional[int]													=	get_resize_output_image_size(__UpperCamelCase     ,size=size['shortest_edge']     ,default_to_square=__UpperCamelCase			)
             elif "height" in size and "width" in size:
                  lowercase_	:				Dict													=	(size['height'], size['width'])
             else:
                  raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase			)			)

        return resize(__UpperCamelCase     ,size=__UpperCamelCase     ,resample=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	get_size_dict(__UpperCamelCase			)
        if "height" not in size or "width" not in size:
             raise ValueError(f'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}'''			)
        return center_crop(__UpperCamelCase     ,size=(size['height'], size['width'])     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      str:


        '''simple docstring'''


        return rescale(__UpperCamelCase     ,scale=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        return normalize(__UpperCamelCase     ,mean=__UpperCamelCase     ,std=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = ChannelDimension.FIRST     ,**__UpperCamelCase     ,)	->      PIL.Image.Image:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	do_resize if do_resize is not None else self.do_resize
        lowercase_	:				Optional[int]													=	crop_pct if crop_pct is not None else self.crop_pct
        lowercase_	:				List[str]													=	resample if resample is not None else self.resample
        lowercase_	:				str													=	do_center_crop if do_center_crop is not None else self.do_center_crop
        lowercase_	:				Tuple													=	do_rescale if do_rescale is not None else self.do_rescale
        lowercase_	:				Union[str, Any]													=	rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_	:				str													=	do_normalize if do_normalize is not None else self.do_normalize
        lowercase_	:				str													=	image_mean if image_mean is not None else self.image_mean
        lowercase_	:				Tuple													=	image_std if image_std is not None else self.image_std

        lowercase_	:				Optional[Any]													=	size if size is not None else self.size
        lowercase_	:				Tuple													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	crop_size if crop_size is not None else self.crop_size
        lowercase_	:				List[str]													=	get_size_dict(__UpperCamelCase     ,param_name='crop_size'			)

        lowercase_	:				str													=	make_list_of_images(__UpperCamelCase			)

        if not valid_images(__UpperCamelCase			):
             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_pct is None:
             raise ValueError('Crop_pct 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.
        lowercase_	:				Optional[Any]													=	[to_numpy_array(__UpperCamelCase			) for image in images]

        if do_resize:
             lowercase_	:				str													=	[self.resize(image=__UpperCamelCase     ,size=__UpperCamelCase     ,crop_pct=__UpperCamelCase     ,resample=__UpperCamelCase			) for image in images]

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

        if do_rescale:
             lowercase_	:				Any													=	[self.rescale(image=__UpperCamelCase     ,scale=__UpperCamelCase			) for image in images]

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

        lowercase_	:				Dict													=	[to_channel_dimension_format(__UpperCamelCase     ,__UpperCamelCase			) for image in images]

        lowercase_	:				Any													=	{'pixel_values': images}
        return BatchFeature(data=__UpperCamelCase     ,tensor_type=__UpperCamelCase			)

