



'''simple docstring'''




import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch

@require_torch
class 			UpperCamelCase_ :





	@property
	def  _lowercase(  self    )			->			int:
								return self.get_dummy_input()





	@property
	def  _lowercase(  self    )			->			Optional[Any]:
								if self.block_type == "down":
															return (4, 32, 16, 16)
								elif self.block_type == "mid":
															return (4, 32, 32, 32)
								elif self.block_type == "up":
															return (4, 32, 64, 64)

								raise ValueError(f'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.'''    )





	def  _lowercase(  self		,		A=True		,		A=False		,		A=False		,		A=False		,		)			->			Tuple:
								UpperCAmelCase     :		Union[str, Any]							     =		4
								UpperCAmelCase     :		Optional[int]							     =		32
								UpperCAmelCase     :		Union[str, Any]							     =		(32, 32)

								UpperCAmelCase     :		str							     =		torch.manual_seed(0    )
								UpperCAmelCase     :		Tuple							     =		torch.device(A    )
								UpperCAmelCase     :		Union[str, Any]							     =		(batch_size, num_channels) + sizes
								UpperCAmelCase     :		Tuple							     =		randn_tensor(A		,		generator=A		,		device=A    )
								UpperCAmelCase     :		Optional[int]							     =		{"""hidden_states""": hidden_states}

								if include_temb:
															UpperCAmelCase     :		Union[str, Any]							     =		128
															UpperCAmelCase     :		Tuple							     =		randn_tensor((batch_size, temb_channels)		,		generator=A		,		device=A    )

								if include_res_hidden_states_tuple:
															UpperCAmelCase     :		Dict							     =		torch.manual_seed(1    )
															UpperCAmelCase     :		Any							     =		(randn_tensor(A		,		generator=A		,		device=A    ),)

								if include_encoder_hidden_states:
															UpperCAmelCase     :		str							     =		floats_tensor((batch_size, 32, 32)    ).to(A    )

								if include_skip_sample:
															UpperCAmelCase     :		List[Any]							     =		randn_tensor(((batch_size, 3) + sizes)		,		generator=A		,		device=A    )

								return dummy_input





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		int							     =		{
								    """in_channels""": 32,
								    """out_channels""": 32,
								    """temb_channels""": 128,
								}
								if self.block_type == "up":
															UpperCAmelCase     :		Optional[Any]							     =		32

								if self.block_type == "mid":
															init_dict.pop("""out_channels"""    )

								UpperCAmelCase     :		List[Any]							     =		self.dummy_input
								return init_dict, inputs_dict





	def  _lowercase(  self		,		A    )			->			Any:
								UpperCAmelCase     ,     UpperCAmelCase     :		List[Any]							     =		self.prepare_init_args_and_inputs_for_common()
								UpperCAmelCase     :		str							     =		self.block_class(**A    )
								unet_block.to(A    )
								unet_block.eval()

								with torch.no_grad():
															UpperCAmelCase     :		Tuple							     =		unet_block(**A    )

								if isinstance(A		,		A    ):
															UpperCAmelCase     :		Optional[int]							     =		output[0]

								self.assertEqual(output.shape		,		self.output_shape    )

								UpperCAmelCase     :		List[str]							     =		output[0, -1, -3:, -3:]
								UpperCAmelCase     :		Union[str, Any]							     =		torch.tensor(A    ).to(A    )
								assert torch_all_close(output_slice.flatten()		,		A		,		atol=5e-3    )






	@unittest.skipIf(torch_device == """mps"""		,		"""Training is not supported in mps"""    )
	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     ,     UpperCAmelCase     :		str							     =		self.prepare_init_args_and_inputs_for_common()
								UpperCAmelCase     :		Union[str, Any]							     =		self.block_class(**A    )
								model.to(A    )
								model.train()
								UpperCAmelCase     :		int							     =		model(**A    )

								if isinstance(A		,		A    ):
															UpperCAmelCase     :		List[str]							     =		output[0]

								UpperCAmelCase     :		Any							     =		torch.device(A    )
								UpperCAmelCase     :		int							     =		randn_tensor(output.shape		,		device=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		torch.nn.functional.mse_loss(A		,		A    )
								loss.backward()






'''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   :			Union[str, Any]					  =    logging.get_logger(__name__)

@add_end_docstrings(__magic_name__			)
class 			UpperCamelCase_ (							__magic_name__			):





	def __init__(  self		,		**A    )			->			List[str]:
								super().__init__(**A    )

								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		,		A		,		**A    )			->			Optional[Any]:
								return super().__call__(A		,		**A    )





	def  _lowercase(  self		,		**A    )			->			Optional[Any]:
								UpperCAmelCase     :		List[Any]							     =		{}
								if "candidate_labels" in kwargs:
															UpperCAmelCase     :		Dict							     =		kwargs["""candidate_labels"""]
								if "hypothesis_template" in kwargs:
															UpperCAmelCase     :		Optional[Any]							     =		kwargs["""hypothesis_template"""]

								return preprocess_params, {}, {}





	def  _lowercase(  self		,		A		,		A=None		,		A="This is a photo of {}."    )			->			Optional[Any]:
								UpperCAmelCase     :		int							     =		load_image(A    )
								UpperCAmelCase     :		List[str]							     =		self.image_processor(images=[image]		,		return_tensors=self.framework    )
								UpperCAmelCase     :		List[str]							     =		candidate_labels
								UpperCAmelCase     :		Tuple							     =		[hypothesis_template.format(A    ) for x in candidate_labels]
								UpperCAmelCase     :		Union[str, Any]							     =		self.tokenizer(A		,		return_tensors=self.framework		,		padding=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		[text_inputs]
								return inputs





	def  _lowercase(  self		,		A    )			->			Optional[int]:
								UpperCAmelCase     :		List[Any]							     =		model_inputs.pop("""candidate_labels"""    )
								UpperCAmelCase     :		Optional[Any]							     =		model_inputs.pop("""text_inputs"""    )
								if isinstance(text_inputs[0]		,		A    ):
															UpperCAmelCase     :		Optional[Any]							     =		text_inputs[0]
								else:
															# Batching case.
															UpperCAmelCase     :		Any							     =		text_inputs[0][0]

								UpperCAmelCase     :		Dict							     =		self.model(**A		,		**A    )

								UpperCAmelCase     :		List[Any]							     =		{
								    """candidate_labels""": candidate_labels,
								    """logits""": outputs.logits_per_image,
								}
								return model_outputs






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

								UpperCAmelCase     :		Any							     =		[
								    {"""score""": score, """label""": candidate_label}
								    for score, candidate_label in sorted(zip(A		,		A    )		,		key=lambda A    : -x[0]    )
								]
								return result

