



'''simple docstring'''

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 		lowerCamelCase__		(						UpperCamelCase__	,   unittest.TestCase     ):




					'''simple docstring'''



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




					@property
					def 						__UpperCAmelCase     (  self				:	str					)  ->       int:



						'''simple docstring'''





						return 32




					@property
					def 						__UpperCAmelCase     (  self				:	Dict					)  ->       Union[str, Any]:



						'''simple docstring'''





						return 32




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



						'''simple docstring'''





						return self.time_input_dim




					@property
					def 						__UpperCAmelCase     (  self				:	Tuple					)  ->       Union[str, Any]:



						'''simple docstring'''





						return self.time_input_dim * 4




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



						'''simple docstring'''





						return 100




					@property
					def 						__UpperCAmelCase     (  self				:	Union[str, Any]					)  ->       Tuple:



						'''simple docstring'''





						torch.manual_seed(0					)

						_lowercase					:       str       =		{
						    """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,
						}

						_lowercase					:       Union[str, Any]       =		UNetaDConditionModel(**_a					)
						return model




					@property
					def 						__UpperCAmelCase     (  self				:	str					)  ->       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				:	Optional[int]					)  ->       Tuple:



						'''simple docstring'''





						torch.manual_seed(0					)
						_lowercase					:       Dict       =		VQModel(**self.dummy_movq_kwargs					)
						return model




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



						'''simple docstring'''





						_lowercase					:       Any       =		self.dummy_unet
						_lowercase					:       List[Any]       =		self.dummy_movq

						_lowercase					:       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,
						}

						_lowercase					:       int       =		DDIMScheduler(**_a					)

						_lowercase					:       Tuple       =		{
						    """unet""": unet,
						    """scheduler""": scheduler,
						    """movq""": movq,
						}

						return components




					def 						__UpperCAmelCase     (  self				:	List[Any]     ,  UpperCamelCase_				:	Any     ,  UpperCamelCase_				:	Tuple=0					)  ->       str:



						'''simple docstring'''





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

						if str(_a					).startswith('mps'					):
							_lowercase					:       Tuple       =		torch.manual_seed(_a					)
						else:
							_lowercase					:       str       =		torch.Generator(device=_a					).manual_seed(_a					)
						_lowercase					:       Optional[Any]       =		{
						    """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				:	int					)  ->       Union[str, Any]:



						'''simple docstring'''





						_lowercase					:       Dict       =		"""cpu"""

						_lowercase					:       int       =		self.get_dummy_components()

						_lowercase					:       Optional[int]       =		self.pipeline_class(**_a					)
						_lowercase					:       Any       =		pipe.to(_a					)

						pipe.set_progress_bar_config(disable=_a					)

						_lowercase					:       List[Any]       =		pipe(**self.get_dummy_inputs(_a					)					)
						_lowercase					:       Dict       =		output.images

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

						_lowercase					:       Dict       =		image[0, -3:, -3:, -1]
						_lowercase					:       Union[str, Any]       =		image_from_tuple[0, -3:, -3:, -1]

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

						_lowercase					:       Optional[int]       =		np.array(
						    [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63]					)
						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     ):




					'''simple docstring'''



					def 						__UpperCAmelCase     (  self				:	Union[str, Any]					)  ->       List[Any]:



						'''simple docstring'''





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




					def 						__UpperCAmelCase     (  self				:	Dict					)  ->       List[str]:



						'''simple docstring'''





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

						_lowercase					:       Union[str, Any]       =		load_image(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'					)
						_lowercase					:       Dict       =		"""A red cartoon frog, 4k"""

						_lowercase					:       Dict       =		KandinskyVaaPriorPipeline.from_pretrained(
						    'kandinsky-community/kandinsky-2-2-prior'     ,  torch_dtype=torch.floataa					)
						pipe_prior.to(_a					)

						_lowercase					:       int       =		KandinskyVaaImgaImgPipeline.from_pretrained(
						    'kandinsky-community/kandinsky-2-2-decoder'     ,  torch_dtype=torch.floataa					)
						_lowercase					:       Dict       =		pipeline.to(_a					)

						pipeline.set_progress_bar_config(disable=_a					)

						_lowercase					:       Tuple       =		torch.Generator(device='cpu'					).manual_seed(0					)
						_lowercase					:       List[str]       =		pipe_prior(
						    _a     ,  generator=_a     ,  num_inference_steps=5     ,  negative_prompt=''     ,  ).to_tuple()

						_lowercase					:       int       =		pipeline(
						    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'     ,  )

						_lowercase					:       Optional[int]       =		output.images[0]

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

						assert_mean_pixel_difference(_a     ,  _a					)





'''simple docstring'''

from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

_A				:    Optional[int]     						=logging.get_logger(__name__)



@add_end_docstrings(A     )
class 		lowerCamelCase__      (						A     ):




					'''simple docstring'''



					def __init__(  self				:	Tuple     ,  **UpperCamelCase_				:	List[str]					)  ->       int:



						'''simple docstring'''





						super().__init__(**UpperCamelCase_					)

						requires_backends(self     ,  'vision'					)
						self.check_model_type(
						    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						    if self.framework == 'tf'
						    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING					)




					def __call__(  self				:	int     ,  UpperCamelCase_				:	Union[str, List[str], "Image", List["Image"]]     ,  **UpperCamelCase_				:	Tuple					)  ->       List[Any]:



						'''simple docstring'''





						return super().__call__(UpperCamelCase_     ,  **UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	List[Any]     ,  **UpperCamelCase_				:	str					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		{}
						if "candidate_labels" in kwargs:
							_lowercase					:       Union[str, Any]       =		kwargs['candidate_labels']
						if "hypothesis_template" in kwargs:
							_lowercase					:       int       =		kwargs['hypothesis_template']

						return preprocess_params, {}, {}




					def 						__UpperCAmelCase     (  self				:	Tuple     ,  UpperCamelCase_				:	Dict     ,  UpperCamelCase_				:	Optional[Any]=None     ,  UpperCamelCase_				:	str="This is a photo of {}."					)  ->       Union[str, Any]:



						'''simple docstring'''





						_lowercase					:       Dict       =		load_image(UpperCamelCase_					)
						_lowercase					:       List[str]       =		self.image_processor(images=[image]     ,  return_tensors=self.framework					)
						_lowercase					:       Optional[Any]       =		candidate_labels
						_lowercase					:       List[Any]       =		[hypothesis_template.format(UpperCamelCase_					) for x in candidate_labels]
						_lowercase					:       Union[str, Any]       =		self.tokenizer(UpperCamelCase_     ,  return_tensors=self.framework     ,  padding=UpperCamelCase_					)
						_lowercase					:       Any       =		[text_inputs]
						return inputs




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



						'''simple docstring'''





						_lowercase					:       Optional[Any]       =		model_inputs.pop('candidate_labels'					)
						_lowercase					:       List[str]       =		model_inputs.pop('text_inputs'					)
						if isinstance(text_inputs[0]     ,  UpperCamelCase_					):
							_lowercase					:       Optional[int]       =		text_inputs[0]
						else:
							# Batching case.
							_lowercase					:       List[str]       =		text_inputs[0][0]

						_lowercase					:       Optional[Any]       =		self.model(**UpperCamelCase_     ,  **UpperCamelCase_					)

						_lowercase					:       Optional[Any]       =		{
						    'candidate_labels': candidate_labels,
						    'logits': outputs.logits_per_image,
						}
						return model_outputs




					def 						__UpperCAmelCase     (  self				:	Optional[int]     ,  UpperCamelCase_				:	int					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		model_outputs.pop('candidate_labels'					)
						_lowercase					:       Optional[int]       =		model_outputs['logits'][0]
						if self.framework == "pt":
							_lowercase					:       List[Any]       =		logits.softmax(dim=-1					).squeeze(-1					)
							_lowercase					:       Tuple       =		probs.tolist()
							if not isinstance(UpperCamelCase_     ,  UpperCamelCase_					):
								_lowercase					:       List[Any]       =		[scores]
						elif self.framework == "tf":
							_lowercase					:       Optional[int]       =		stable_softmax(UpperCamelCase_     ,  axis=-1					)
							_lowercase					:       List[Any]       =		probs.numpy().tolist()
						else:
							raise ValueError(F'''Unsupported framework: {self.framework}'''					)

						_lowercase					:       List[Any]       =		[
						    {'score': score, 'label': candidate_label}
						    for score, candidate_label in sorted(zip(UpperCamelCase_     ,  UpperCamelCase_					)     ,  key=lambda UpperCamelCase_					: -x[0]					)
						]
						return result
