from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


__lowerCamelCase   :						List[Any]				=			logging.get_logger(__name__)  # pylint: disable=invalid-name

__lowerCamelCase   :						Union[str, Any]				=			"\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to(\"cuda\")\n\n        >>> prompt = \"A red cartoon frog, 4k\"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to(\"cuda\")\n\n        >>> init_image = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/frog.png\"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save(\"red_frog.png\")\n        ```\n"







def 		lowercase__   (		__A:	Tuple							,__A:	Union[str, Any]							,__A:	List[Any]=8				):





					'''simple docstring'''






					__magic_name__							:	List[Any]    							=							height // scale_factor**2
					if height % scale_factor**2 != 0:
										new_height += 1
					__magic_name__							:	List[str]    							=							width // scale_factor**2
					if width % scale_factor**2 != 0:
										new_width += 1
					return new_height * scale_factor, new_width * scale_factor







def 		lowercase__   (		__A:	Any							,__A:	Dict=5_1_2							,__A:	Optional[Any]=5_1_2				):





					'''simple docstring'''






					__magic_name__							:	int    							=							pil_image.resize((w, h)							,resample=Image.BICUBIC							,reducing_gap=1				)
					__magic_name__							:	int    							=							np.array(pil_image.convert('''RGB'''				)				)
					__magic_name__							:	Optional[int]    							=							arr.astype(np.floataa				) / 1_2_7.5 - 1
					__magic_name__							:	Any    							=							np.transpose(__A							,[2, 0, 1]				)
					__magic_name__							:	Any    							=							torch.from_numpy(__A				).unsqueeze(0				)
					return image


class    lowerCamelCase    (		UpperCAmelCase_						):






			'''simple docstring'''





			def __init__( self			:   int       ,						lowerCamelCase_			:   str       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   str       ,						)						->   List[Any]:
								super().__init__()

								self.register_modules(
								    unet=_lowercase       ,						scheduler=_lowercase       ,						movq=_lowercase       ,						)
								__magic_name__							:	Dict    							=							2 ** (len(self.movq.config.block_out_channels  ) - 1)

			def 							UpperCAmelCase__       ( self			:   int       ,						lowerCamelCase_			:   Any       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Optional[int]  )						->   int:
								# get the original timestep using init_timestep
								__magic_name__							:	List[Any]    							=							min(int(num_inference_steps * strength  )       ,						_lowercase  )

								__magic_name__							:	Tuple    							=							max(num_inference_steps - init_timestep       ,						0  )
								__magic_name__							:	Optional[Any]    							=							self.scheduler.timesteps[t_start:]

								return timesteps, num_inference_steps - t_start

			def 							UpperCAmelCase__       ( self			:   Tuple       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   int=None  )						->   Any:
								if not isinstance(_lowercase       ,						(torch.Tensor, PIL.Image.Image, list)  ):
													raise ValueError(
													    F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_lowercase  )}'''  )

								__magic_name__							:	Dict    							=							image.to(device=_lowercase       ,						dtype=_lowercase  )

								__magic_name__							:	Dict    							=							batch_size * num_images_per_prompt

								if image.shape[1] == 4:
													__magic_name__							:	str    							=							image

								else:
													if isinstance(_lowercase       ,						_lowercase  ) and len(_lowercase  ) != batch_size:
																		raise ValueError(
																		    F'''You have passed a list of generators of length {len(_lowercase  )}, but requested an effective batch'''
																		    F''' size of {batch_size}. Make sure the batch size matches the length of the generators.'''  )

													elif isinstance(_lowercase       ,						_lowercase  ):
																		__magic_name__							:	List[Any]    							=							[
																		    self.movq.encode(image[i : i + 1]  ).latent_dist.sample(generator[i]  ) for i in range(_lowercase  )
																		]
																		__magic_name__							:	Union[str, Any]    							=							torch.cat(_lowercase       ,						dim=0  )
													else:
																		__magic_name__							:	Union[str, Any]    							=							self.movq.encode(_lowercase  ).latent_dist.sample(_lowercase  )

													__magic_name__							:	str    							=							self.movq.config.scaling_factor * init_latents

								__magic_name__							:	int    							=							torch.cat([init_latents]       ,						dim=0  )

								__magic_name__							:	Dict    							=							init_latents.shape
								__magic_name__							:	Dict    							=							randn_tensor(_lowercase       ,						generator=_lowercase       ,						device=_lowercase       ,						dtype=_lowercase  )

								# get latents
								__magic_name__							:	List[str]    							=							self.scheduler.add_noise(_lowercase       ,						_lowercase       ,						_lowercase  )

								__magic_name__							:	Optional[Any]    							=							init_latents

								return latents

			def 							UpperCAmelCase__       ( self			:   List[Any]       ,						lowerCamelCase_			:   Tuple=0  )						->   int:
								if is_accelerate_available():
													from accelerate import cpu_offload
								else:
													raise ImportError('''Please install accelerate via `pip install accelerate`'''  )

								__magic_name__							:	List[Any]    							=							torch.device(F'''cuda:{gpu_id}'''  )

								__magic_name__							:	Optional[Any]    							=							[
								    self.unet,
								    self.movq,
								]
								for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																		cpu_offload(_lowercase       ,						_lowercase  )

			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Optional[Any]=0  )						->   int:
								if is_accelerate_available() and is_accelerate_version('''>='''       ,						'''0.17.0.dev0'''  ):
													from accelerate import cpu_offload_with_hook
								else:
													raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''  )

								__magic_name__							:	List[Any]    							=							torch.device(F'''cuda:{gpu_id}'''  )

								if self.device.type != "cpu":
													self.to('''cpu'''       ,						silence_dtype_warnings=_lowercase  )
													torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

								__magic_name__							:	Tuple    							=							None
								for cpu_offloaded_model in [self.unet, self.movq]:
													__magic_name__							:	Dict    							=							cpu_offload_with_hook(_lowercase       ,						_lowercase       ,						prev_module_hook=_lowercase  )

								# We'll offload the last model manually.
								__magic_name__							:	List[str]    							=							hook

			@property
			# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
			def 							UpperCAmelCase__       ( self			:   str  )						->   List[str]:
								if not hasattr(self.unet       ,						'''_hf_hook'''  ):
													return self.device
								for module in self.unet.modules():
													if (
													    hasattr(_lowercase       ,						'''_hf_hook'''  )
													    and hasattr(module._hf_hook       ,						'''execution_device'''  )
													    and module._hf_hook.execution_device is not None
													):
																		return torch.device(module._hf_hook.execution_device  )
								return self.device


			@torch.no_grad()
			@replace_example_docstring(_lowercase  )
			def __call__( self			:   Any       ,						lowerCamelCase_			:   Dict       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Dict = 512       ,						lowerCamelCase_			:   Union[str, Any] = 512       ,						lowerCamelCase_			:   Optional[Any] = 100       ,						lowerCamelCase_			:   Optional[int] = 4.0       ,						lowerCamelCase_			:   Tuple = 0.3       ,						lowerCamelCase_			:   List[str] = 1       ,						lowerCamelCase_			:   Union[str, Any] = None       ,						lowerCamelCase_			:   Tuple = "pil"       ,						lowerCamelCase_			:   Optional[int] = True       ,						)						->   str:
								__magic_name__							:	List[Any]    							=							self._execution_device

								__magic_name__							:	List[Any]    							=							guidance_scale > 1.0

								if isinstance(_lowercase       ,						_lowercase  ):
													__magic_name__							:	Union[str, Any]    							=							torch.cat(_lowercase       ,						dim=0  )
								__magic_name__							:	Optional[Any]    							=							image_embeds.shape[0]
								if isinstance(_lowercase       ,						_lowercase  ):
													__magic_name__							:	List[str]    							=							torch.cat(_lowercase       ,						dim=0  )

								if do_classifier_free_guidance:
													__magic_name__							:	List[str]    							=							image_embeds.repeat_interleave(_lowercase       ,						dim=0  )
													__magic_name__							:	Dict    							=							negative_image_embeds.repeat_interleave(_lowercase       ,						dim=0  )

								__magic_name__							:	Dict    							=							torch.cat([negative_image_embeds, image_embeds]       ,						dim=0  ).to(dtype=self.unet.dtype       ,						device=_lowercase  )

								if not isinstance(_lowercase       ,						_lowercase  ):
													__magic_name__							:	Union[str, Any]    							=							[image]
								if not all(isinstance(_lowercase       ,						(PIL.Image.Image, torch.Tensor)  ) for i in image  ):
													raise ValueError(
													    F'''Input is in incorrect format: {[type(_lowercase  ) for i in image]}. Currently, we only support  PIL image and pytorch tensor'''  )

								__magic_name__							:	List[Any]    							=							torch.cat([prepare_image(_lowercase       ,						_lowercase       ,						_lowercase  ) for i in image]       ,						dim=0  )
								__magic_name__							:	Dict    							=							image.to(dtype=image_embeds.dtype       ,						device=_lowercase  )

								__magic_name__							:	Dict    							=							self.movq.encode(_lowercase  )['latents']
								__magic_name__							:	Optional[Any]    							=							latents.repeat_interleave(_lowercase       ,						dim=0  )
								self.scheduler.set_timesteps(_lowercase       ,						device=_lowercase  )
								__magic_name__							:	str    							=							self.get_timesteps(_lowercase       ,						_lowercase       ,						_lowercase  )
								__magic_name__							:	int    							=							timesteps[:1].repeat(batch_size * num_images_per_prompt  )
								__magic_name__							:	Union[str, Any]    							=							downscale_height_and_width(_lowercase       ,						_lowercase       ,						self.movq_scale_factor  )
								__magic_name__							:	List[str]    							=							self.prepare_latents(
								    _lowercase       ,						_lowercase       ,						_lowercase       ,						_lowercase       ,						image_embeds.dtype       ,						_lowercase       ,						_lowercase  )
								for i, t in enumerate(self.progress_bar(_lowercase  )  ):
													# expand the latents if we are doing classifier free guidance
													__magic_name__							:	int    							=							torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents

													__magic_name__							:	str    							=							{'image_embeds': image_embeds}
													__magic_name__							:	str    							=							self.unet(
													    sample=_lowercase       ,						timestep=_lowercase       ,						encoder_hidden_states=_lowercase       ,						added_cond_kwargs=_lowercase       ,						return_dict=_lowercase       ,						)[0]

													if do_classifier_free_guidance:
																		__magic_name__							:	Dict    							=							noise_pred.split(latents.shape[1]       ,						dim=1  )
																		__magic_name__							:	Optional[int]    							=							noise_pred.chunk(2  )
																		__magic_name__							:	Tuple    							=							variance_pred.chunk(2  )
																		__magic_name__							:	List[str]    							=							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																		__magic_name__							:	Tuple    							=							torch.cat([noise_pred, variance_pred_text]       ,						dim=1  )

													if not (
													    hasattr(self.scheduler.config       ,						'''variance_type'''  )
													    and self.scheduler.config.variance_type in ["learned", "learned_range"]
													):
																		__magic_name__							:	List[str]    							=							noise_pred.split(latents.shape[1]       ,						dim=1  )

													# compute the previous noisy sample x_t -> x_t-1
													__magic_name__							:	Dict    							=							self.scheduler.step(
													    _lowercase       ,						_lowercase       ,						_lowercase       ,						generator=_lowercase       ,						)[0]

								# post-processing
								__magic_name__							:	Any    							=							self.movq.decode(_lowercase       ,						force_not_quantize=_lowercase  )['sample']

								if output_type not in ["pt", "np", "pil"]:
													raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''  )

								if output_type in ["np", "pil"]:
													__magic_name__							:	Dict    							=							image * 0.5 + 0.5
													__magic_name__							:	Dict    							=							image.clamp(0       ,						1  )
													__magic_name__							:	int    							=							image.cpu().permute(0       ,						2       ,						3       ,						1  ).float().numpy()

								if output_type == "pil":
													__magic_name__							:	int    							=							self.numpy_to_pil(_lowercase  )

								if not return_dict:
													return (image,)

								return ImagePipelineOutput(images=_lowercase  )









import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					return 1.0 / (1.0 + np.exp(-_outputs				))







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






					__magic_name__							:	List[str]    							=							np.max(_outputs							,axis=-1							,keepdims=__A				)
					__magic_name__							:	int    							=							np.exp(_outputs - maxes				)
					return shifted_exp / shifted_exp.sum(axis=-1							,keepdims=__A				)


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								='''sigmoid'''
			UpperCamelCase__								='''softmax'''
			UpperCamelCase__								='''none'''






@add_end_docstrings(
    _lowerCamelCase				,R'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''				,)
class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=False
			UpperCamelCase__								=ClassificationFunction.NONE

			def __init__( self			:   Tuple       ,						**lowerCamelCase_			:   Tuple  )						->   List[Any]:
								super().__init__(**lowerCamelCase_  )

								self.check_model_type(
								    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
								    if self.framework == '''tf'''
								    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   Tuple=None       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   Optional[int]=""       ,						**lowerCamelCase_			:   int  )						->   str:
								# Using "" as default argument because we're going to use `top_k=None` in user code to declare
								# "No top_k"
								__magic_name__							:	Dict    							=							tokenizer_kwargs

								__magic_name__							:	Dict    							=							{}
								if hasattr(self.model.config       ,						'''return_all_scores'''  ) and return_all_scores is None:
													__magic_name__							:	List[str]    							=							self.model.config.return_all_scores

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) or top_k is None:
													__magic_name__							:	Dict    							=							top_k
													__magic_name__							:	List[Any]    							=							False
								elif return_all_scores is not None:
													warnings.warn(
													    '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
													    ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''       ,						lowerCamelCase_       ,						)
													if return_all_scores:
																		__magic_name__							:	str    							=							None
													else:
																		__magic_name__							:	int    							=							1

								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													__magic_name__							:	str    							=							ClassificationFunction[function_to_apply.upper()]

								if function_to_apply is not None:
													__magic_name__							:	List[str]    							=							function_to_apply
								return preprocess_params, {}, postprocess_params

			def __call__( self			:   Optional[Any]       ,						*lowerCamelCase_			:   Union[str, Any]       ,						**lowerCamelCase_			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							:	Optional[int]    							=							super().__call__(*lowerCamelCase_       ,						**lowerCamelCase_  )
								# TODO try and retrieve it in a nicer way from _sanitize_parameters.
								__magic_name__							:	int    							=							'''top_k''' not in kwargs
								if isinstance(args[0]       ,						lowerCamelCase_  ) and _legacy:
													# This pipeline is odd, and return a list when single item is run
													return [result]
								else:
													return result

			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Any       ,						**lowerCamelCase_			:   int  )						->   Dict[str, GenericTensor]:
								__magic_name__							:	Union[str, Any]    							=							self.framework
								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													return self.tokenizer(**lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and len(lowerCamelCase_  ) == 1 and isinstance(inputs[0]       ,						lowerCamelCase_  ) and len(inputs[0]  ) == 2:
													# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
													return self.tokenizer(
													    text=inputs[0][0]       ,						text_pair=inputs[0][1]       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													# This is likely an invalid usage of the pipeline attempting to pass text pairs.
													raise ValueError(
													    '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
													    ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''  )
								return self.tokenizer(lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   str       ,						lowerCamelCase_			:   Dict  )						->   Union[str, Any]:
								return self.model(**lowerCamelCase_  )


			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Dict       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   List[str]=1       ,						lowerCamelCase_			:   Any=True  )						->   int:
								# `_legacy` is used to determine if we're running the naked pipeline and in backward
								# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
								# the more natural result containing the list.
								# Default value before `set_parameters`
								if function_to_apply is None:
													if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																		__magic_name__							:	Union[str, Any]    							=							ClassificationFunction.SIGMOID
													elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																		__magic_name__							:	str    							=							ClassificationFunction.SOFTMAX
													elif hasattr(self.model.config       ,						'''function_to_apply'''  ) and function_to_apply is None:
																		__magic_name__							:	Dict    							=							self.model.config.function_to_apply
													else:
																		__magic_name__							:	Optional[Any]    							=							ClassificationFunction.NONE

								__magic_name__							:	Any    							=							model_outputs['''logits'''][0]
								__magic_name__							:	Optional[int]    							=							outputs.numpy()

								if function_to_apply == ClassificationFunction.SIGMOID:
													__magic_name__							:	List[str]    							=							sigmoid(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.SOFTMAX:
													__magic_name__							:	Optional[int]    							=							softmax(lowerCamelCase_  )
								elif function_to_apply == ClassificationFunction.NONE:
													__magic_name__							:	Optional[int]    							=							outputs
								else:
													raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}'''  )

								if top_k == 1 and _legacy:
													return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

								__magic_name__							:	Union[str, Any]    							=							[
								    {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(lowerCamelCase_  )
								]
								if not _legacy:
													dict_scores.sort(key=lambda lowerCamelCase_  : x["score"]       ,						reverse=lowerCamelCase_  )
													if top_k is not None:
																		__magic_name__							:	Dict    							=							dict_scores[:top_k]
								return dict_scores



