




import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    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   A(						UpperCamelCase							,				unittest.TestCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						KandinskyVaaImgaImgPipeline
 UpperCamelCase						       =						['''image_embeds''', '''negative_image_embeds''', '''image''']
 UpperCamelCase						       =						[
     '''image_embeds''',
     '''negative_image_embeds''',
     '''image''',
 ]
 UpperCamelCase						       =						[
     '''generator''',
     '''height''',
     '''width''',
     '''strength''',
     '''guidance_scale''',
     '''num_inference_steps''',
     '''return_dict''',
     '''guidance_scale''',
     '''num_images_per_prompt''',
     '''output_type''',
     '''return_dict''',
 ]
 UpperCamelCase						       =						False

 @property
 def     a__			(    self :  Optional[Any]  )       ->     int:

       """simple docstring"""






       return 32

 @property
 def     a__			(    self :  Union[str, Any]  )       ->     Optional[Any]:

       """simple docstring"""






       return 32

 @property
 def     a__			(    self :  List[str]  )       ->     str:

       """simple docstring"""






       return self.time_input_dim

 @property
 def     a__			(    self :  int  )       ->     Optional[int]:

       """simple docstring"""






       return self.time_input_dim * 4

 @property
 def     a__			(    self :  Tuple  )       ->     Optional[int]:

       """simple docstring"""






       return 100

 @property
 def     a__			(    self :  Optional[int]  )       ->     str:

       """simple docstring"""






       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': '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_							=   UNetaDConditionModel(**lowercase_  )
       return model

 @property
 def     a__			(    self :  List[Any]  )       ->     Any:

       """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     a__			(    self :  List[str]  )       ->     str:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_							=   VQModel(**self.dummy_movq_kwargs  )
       return model

 def     a__			(    self :  Optional[Any]  )       ->     Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_							=   self.dummy_unet
       lowerCamelCase_							=   self.dummy_movq

       lowerCamelCase_							=   {
           'num_train_timesteps': 1000,
           'beta_schedule': 'linear',
           'beta_start': 0.00085,
           'beta_end': 0.012,
           'clip_sample': False,
           'set_alpha_to_one': False,
           'steps_offset': 0,
           'prediction_type': 'epsilon',
           'thresholding': False,
       }

       lowerCamelCase_							=   DDIMScheduler(**lowercase_  )

       lowerCamelCase_							=   {
           'unet': unet,
           'scheduler': scheduler,
           'movq': movq,
       }

       return components

 def     a__			(    self :  int						,							A_ :  Dict						,							A_ :  Optional[Any]=0  )       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   floats_tensor((1, self.text_embedder_hidden_size)						,							rng=random.Random(lowercase_  )  ).to(lowercase_  )
       lowerCamelCase_							=   floats_tensor((1, self.text_embedder_hidden_size)						,							rng=random.Random(seed + 1  )  ).to(
           lowercase_  )
       # create init_image
       lowerCamelCase_							=   floats_tensor((1, 3, 64, 64)						,							rng=random.Random(lowercase_  )  ).to(lowercase_  )
       lowerCamelCase_							=   image.cpu().permute(0						,							2						,							3						,							1  )[0]
       lowerCamelCase_							=   Image.fromarray(np.uinta(lowercase_  )  ).convert('RGB'  ).resize((256, 256)  )

       if str(lowercase_  ).startswith('mps'  ):
             lowerCamelCase_							=   torch.manual_seed(lowercase_  )
       else:
             lowerCamelCase_							=   torch.Generator(device=lowercase_  ).manual_seed(lowercase_  )
       lowerCamelCase_							=   {
           '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     a__			(    self :  Optional[Any]  )       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   'cpu'

       lowerCamelCase_							=   self.get_dummy_components()

       lowerCamelCase_							=   self.pipeline_class(**lowercase_  )
       lowerCamelCase_							=   pipe.to(lowercase_  )

       pipe.set_progress_bar_config(disable=lowercase_  )

       lowerCamelCase_							=   pipe(**self.get_dummy_inputs(lowercase_  )  )
       lowerCamelCase_							=   output.images

       lowerCamelCase_							=   pipe(
           **self.get_dummy_inputs(lowercase_  )						,							return_dict=lowercase_						,							)[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.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263]  )
       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       ):



 '''simple docstring'''


 def     a__			(    self :  int  )       ->     Any:

       """simple docstring"""






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





 def     a__			(    self :  Tuple  )       ->     Union[str, Any]:

       """simple docstring"""






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

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

       lowerCamelCase_							=   KandinskyVaaPriorPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-2-prior'						,							torch_dtype=torch.floataa  )
       pipe_prior.to(lowercase_  )

       lowerCamelCase_							=   KandinskyVaaImgaImgPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-2-decoder'						,							torch_dtype=torch.floataa  )
       lowerCamelCase_							=   pipeline.to(lowercase_  )

       pipeline.set_progress_bar_config(disable=lowercase_  )

       lowerCamelCase_							=   torch.Generator(device='cpu'  ).manual_seed(0  )
       lowerCamelCase_					,    lowerCamelCase_							=   pipe_prior(
           lowercase_						,							generator=lowercase_						,							num_inference_steps=5						,							negative_prompt=''						,							).to_tuple()

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

       lowerCamelCase_							=   output.images[0]

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

       assert_mean_pixel_difference(lowercase_						,							lowercase_  )






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ChineseCLIPImageProcessor







class   A(						unittest.TestCase       ):



 '''simple docstring'''


 def __init__(    self :  str						,							A_ :  int						,							A_ :  Any=7						,							A_ :  Tuple=3						,							A_ :  Union[str, Any]=18						,							A_ :  Tuple=30						,							A_ :  Union[str, Any]=400						,							A_ :  Optional[int]=True						,							A_ :  List[Any]=None						,							A_ :  Dict=True						,							A_ :  Union[str, Any]=None						,							A_ :  Optional[int]=True						,							A_ :  str=[0.48145466, 0.4578275, 0.40821073]						,							A_ :  Tuple=[0.26862954, 0.26130258, 0.27577711]						,							A_ :  Any=True						,							)       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   size if size is not None else {'height': 224, 'width': 224}
       lowerCamelCase_							=   crop_size if crop_size is not None else {'height': 18, 'width': 18}
       lowerCamelCase_							=   parent
       lowerCamelCase_							=   batch_size
       lowerCamelCase_							=   num_channels
       lowerCamelCase_							=   image_size
       lowerCamelCase_							=   min_resolution
       lowerCamelCase_							=   max_resolution
       lowerCamelCase_							=   do_resize
       lowerCamelCase_							=   size
       lowerCamelCase_							=   do_center_crop
       lowerCamelCase_							=   crop_size
       lowerCamelCase_							=   do_normalize
       lowerCamelCase_							=   image_mean
       lowerCamelCase_							=   image_std
       lowerCamelCase_							=   do_convert_rgb

 def     a__			(    self :  Optional[int]  )       ->     Tuple:

       """simple docstring"""






       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_center_crop": self.do_center_crop,
           "crop_size": self.crop_size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_convert_rgb": self.do_convert_rgb,
       }





 def     a__			(    self :  Any						,							A_ :  Any=False						,							A_ :  Dict=False						,							A_ :  str=False  )       ->     Union[str, Any]:

       """simple docstring"""






       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

       if equal_resolution:
             lowerCamelCase_							=   []
             for i in range(self.batch_size  ):
                   image_inputs.append(
                       np.random.randint(
                           255						,							size=(self.num_channels, self.max_resolution, self.max_resolution)						,							dtype=np.uinta  )  )
       else:
             lowerCamelCase_							=   []
             for i in range(self.batch_size  ):
                   lowerCamelCase_					,    lowerCamelCase_							=   np.random.choice(np.arange(self.min_resolution						,							self.max_resolution  )						,							2  )
                   image_inputs.append(np.random.randint(255						,							size=(self.num_channels, width, height)						,							dtype=np.uinta  )  )

       if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             lowerCamelCase_							=   [Image.fromarray(np.moveaxis(A_						,							0						,							-1  )  ) for x in image_inputs]

       if torchify:
             lowerCamelCase_							=   [torch.from_numpy(A_  ) for x in image_inputs]

       return image_inputs







@require_torch
@require_vision
class   A(						UpperCamelCase							,				unittest.TestCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						ChineseCLIPImageProcessor if is_vision_available() else None

 def     a__			(    self :  int  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   ChineseCLIPImageProcessingTester(self						,							do_center_crop=A_  )

 @property
 def     a__			(    self :  str  )       ->     List[Any]:

       """simple docstring"""






       return self.image_processor_tester.prepare_image_processor_dict()

 def     a__			(    self :  int  )       ->     Optional[Any]:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       self.assertTrue(hasattr(A_						,							'do_resize'  )  )
       self.assertTrue(hasattr(A_						,							'size'  )  )
       self.assertTrue(hasattr(A_						,							'do_center_crop'  )  )
       self.assertTrue(hasattr(A_						,							'center_crop'  )  )
       self.assertTrue(hasattr(A_						,							'do_normalize'  )  )
       self.assertTrue(hasattr(A_						,							'image_mean'  )  )
       self.assertTrue(hasattr(A_						,							'image_std'  )  )
       self.assertTrue(hasattr(A_						,							'do_convert_rgb'  )  )

 def     a__			(    self :  Any  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class.from_dict(self.image_processor_dict  )
       self.assertEqual(image_processor.size						,							{'height': 224, 'width': 224}  )
       self.assertEqual(image_processor.crop_size						,							{'height': 18, 'width': 18}  )

       lowerCamelCase_							=   self.image_processing_class.from_dict(self.image_processor_dict						,							size=42						,							crop_size=84  )
       self.assertEqual(image_processor.size						,							{'shortest_edge': 42}  )
       self.assertEqual(image_processor.crop_size						,							{'height': 84, 'width': 84}  )

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

       """simple docstring"""






       pass

 def     a__			(    self :  str  )       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowerCamelCase_							=   self.image_processor_tester.prepare_inputs(equal_resolution=A_  )
       for image in image_inputs:
             self.assertIsInstance(A_						,							Image.Image  )

       # Test not batched input
       lowerCamelCase_							=   image_processing(image_inputs[0]						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)

       # Test batched
       lowerCamelCase_							=   image_processing(A_						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)

 def     a__			(    self :  List[str]  )       ->     Optional[Any]:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       # create random numpy tensors
       lowerCamelCase_							=   self.image_processor_tester.prepare_inputs(equal_resolution=A_						,							numpify=A_  )
       for image in image_inputs:
             self.assertIsInstance(A_						,							np.ndarray  )

       # Test not batched input
       lowerCamelCase_							=   image_processing(image_inputs[0]						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)

       # Test batched
       lowerCamelCase_							=   image_processing(A_						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)





 def     a__			(    self :  str  )       ->     Dict:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       # create random PyTorch tensors
       lowerCamelCase_							=   self.image_processor_tester.prepare_inputs(equal_resolution=A_						,							torchify=A_  )
       for image in image_inputs:
             self.assertIsInstance(A_						,							torch.Tensor  )

       # Test not batched input
       lowerCamelCase_							=   image_processing(image_inputs[0]						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)

       # Test batched
       lowerCamelCase_							=   image_processing(A_						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)







@require_torch
@require_vision
class   A(						UpperCamelCase							,				unittest.TestCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						ChineseCLIPImageProcessor if is_vision_available() else None

 def     a__			(    self :  Dict  )       ->     int:

       """simple docstring"""






       lowerCamelCase_							=   ChineseCLIPImageProcessingTester(self						,							num_channels=4						,							do_center_crop=A_  )
       lowerCamelCase_							=   3

 @property
 def     a__			(    self :  Any  )       ->     int:

       """simple docstring"""






       return self.image_processor_tester.prepare_image_processor_dict()

 def     a__			(    self :  Dict  )       ->     Tuple:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       self.assertTrue(hasattr(A_						,							'do_resize'  )  )
       self.assertTrue(hasattr(A_						,							'size'  )  )
       self.assertTrue(hasattr(A_						,							'do_center_crop'  )  )
       self.assertTrue(hasattr(A_						,							'center_crop'  )  )
       self.assertTrue(hasattr(A_						,							'do_normalize'  )  )
       self.assertTrue(hasattr(A_						,							'image_mean'  )  )
       self.assertTrue(hasattr(A_						,							'image_std'  )  )
       self.assertTrue(hasattr(A_						,							'do_convert_rgb'  )  )

 def     a__			(    self :  Tuple  )       ->     List[str]:

       """simple docstring"""






       pass





 def     a__			(    self :  Union[str, Any]  )       ->     int:

       """simple docstring"""






       lowerCamelCase_							=   self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowerCamelCase_							=   self.image_processor_tester.prepare_inputs(equal_resolution=A_  )
       for image in image_inputs:
             self.assertIsInstance(A_						,							Image.Image  )

       # Test not batched input
       lowerCamelCase_							=   image_processing(image_inputs[0]						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               1,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)

       # Test batched
       lowerCamelCase_							=   image_processing(A_						,							return_tensors='pt'  ).pixel_values
       self.assertEqual(
           encoded_images.shape						,							(
               self.image_processor_tester.batch_size,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )						,							)



