




"""simple docstring"""

from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


_lowerCamelCase					:     List[str]				       =    getLogger(__name__)


_lowerCamelCase					:     Union[str, Any]				       =    4
_lowerCamelCase					:     int				       =    7

_lowerCamelCase					:     List[Any]				       =    {
    'float16': torch.floataa,
    'float32': torch.floataa,
}

def 						lowercase_ (						_UpperCAmelCase		):




	"""simple docstring"""






	if isinstance(_UpperCAmelCase					, torch.Tensor		):
		return image
	elif isinstance(_UpperCAmelCase					, PIL.Image.Image		):
		A_					:			Dict						=						[image]

	if isinstance(image[0]					, PIL.Image.Image		):
		A_				,	A_					:			List[str]						=						image[0].size
		A_				,	A_					:			Any						=						(x - x % 64 for x in (w, h))  # resize to integer multiple of 32

		A_					:			Optional[int]						=						[np.array(i.resize((w, h)		)		)[None, :] for i in image]
		A_					:			Any						=						np.concatenate(_UpperCAmelCase					, axis=0		)
		A_					:			int						=						np.array(_UpperCAmelCase		).astype(np.floataa		) / 255.0
		A_					:			str						=						image.transpose(0					, 3					, 1					, 2		)
		A_					:			Optional[int]						=						2.0 * image - 1.0
		A_					:			Dict						=						torch.from_numpy(_UpperCAmelCase		)
	elif isinstance(image[0]					, torch.Tensor		):
		A_					:			Union[str, Any]						=						torch.cat(_UpperCAmelCase					, dim=0		)

	return image

class     lowercase (      __UpperCAmelCase):







				def __init__(							self				:   Optional[Any] ,       _lowerCamelCase				:   OnnxRuntimeModel ,       _lowerCamelCase				:   OnnxRuntimeModel ,       _lowerCamelCase				:   Any ,       _lowerCamelCase				:   OnnxRuntimeModel ,       _lowerCamelCase				:   DDPMScheduler ,       _lowerCamelCase				:   Any ,       _lowerCamelCase				:   int = 3_50 ,       ):



					"""simple docstring"""

					super().__init__(
					    vae=_lowerCamelCase ,       text_encoder=_lowerCamelCase ,       tokenizer=_lowerCamelCase ,       unet=_lowerCamelCase ,       low_res_scheduler=_lowerCamelCase ,       scheduler=_lowerCamelCase ,       safety_checker=_lowerCamelCase ,       feature_extractor=_lowerCamelCase ,       watermarker=_lowerCamelCase ,       max_noise_level=_lowerCamelCase ,       )







				def __call__(							self				:   Optional[int] ,       _lowerCamelCase				:   Union[str, List[str]] ,       _lowerCamelCase				:   Union[torch.FloatTensor, PIL.Image.Image, List[PIL.Image.Image]] ,       _lowerCamelCase				:   int = 75 ,       _lowerCamelCase				:   float = 9.0 ,       _lowerCamelCase				:   int = 20 ,       _lowerCamelCase				:   Optional[Union[str, List[str]]] = None ,       _lowerCamelCase				:   Optional[int] = 1 ,       _lowerCamelCase				:   float = 0.0 ,       _lowerCamelCase				:   Optional[Union[torch.Generator, List[torch.Generator]]] = None ,       _lowerCamelCase				:   Optional[torch.FloatTensor] = None ,       _lowerCamelCase				:   Optional[np.ndarray] = None ,       _lowerCamelCase				:   Optional[np.ndarray] = None ,       _lowerCamelCase				:   Optional[str] = "pil" ,       _lowerCamelCase				:   bool = True ,       _lowerCamelCase				:   Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,       _lowerCamelCase				:   Optional[int] = 1 ,       ):



					"""simple docstring"""

					self.check_inputs(_lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase    )

					# 2. Define call parameters
					if prompt is not None and isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
						A_					:			Union[str, Any]						=						1
					elif prompt is not None and isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
						A_					:			List[str]						=						len(_lowerCamelCase    )
					else:
						A_					:			int						=						prompt_embeds.shape[0]

					A_					:			List[Any]						=						self._execution_device
					# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
					# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
					# corresponds to doing no classifier free guidance.
					A_					:			List[Any]						=						guidance_scale > 1.0

					# 3. Encode input prompt
					A_					:			Any						=						self._encode_prompt(
					    _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       prompt_embeds=_lowerCamelCase ,       negative_prompt_embeds=_lowerCamelCase ,       )

					A_					:			Tuple						=						ORT_TO_PT_TYPE[str(text_embeddings.dtype    )]

					# 4. Preprocess image
					A_					:			Optional[int]						=						preprocess(_lowerCamelCase    )
					A_					:			Tuple						=						image.cpu()

					# 5. set timesteps
					self.scheduler.set_timesteps(_lowerCamelCase ,       device=_lowerCamelCase    )
					A_					:			Optional[Any]						=						self.scheduler.timesteps

					# 5. Add noise to image
					A_					:			Optional[Any]						=						torch.tensor([noise_level] ,       dtype=torch.long ,       device=_lowerCamelCase    )
					A_					:			Union[str, Any]						=						torch.randn(image.shape ,       generator=_lowerCamelCase ,       device=_lowerCamelCase ,       dtype=_lowerCamelCase    )
					A_					:			List[Any]						=						self.low_res_scheduler.add_noise(_lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase    )

					A_					:			int						=						2 if do_classifier_free_guidance else 1
					A_					:			int						=						np.concatenate([image] * batch_multiplier * num_images_per_prompt    )
					A_					:			Optional[int]						=						np.concatenate([noise_level] * image.shape[0]    )

					# 6. Prepare latent variables
					A_				,	A_					:			Tuple						=						image.shape[2:]
					A_					:			List[str]						=						self.prepare_latents(
					    batch_size * num_images_per_prompt ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       )

					# 7. Check that sizes of image and latents match
					A_					:			Dict						=						image.shape[1]
					if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
						raise ValueError(
						    '''Incorrect configuration settings! The config of `pipeline.unet` expects'''
						    F""" {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +"""
						    F""" `num_channels_image`: {num_channels_image} """
						    F""" = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of"""
						    ''' `pipeline.unet` or your `image` input.'''    )

					# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
					A_					:			Union[str, Any]						=						self.prepare_extra_step_kwargs(_lowerCamelCase ,       _lowerCamelCase    )

					A_					:			List[str]						=						next(
					    (input.type for input in self.unet.model.get_inputs() if input.name == '''timestep''') ,       '''tensor(float)'''    )
					A_					:			int						=						ORT_TO_NP_TYPE[timestep_dtype]

					# 9. Denoising loop
					A_					:			int						=						len(_lowerCamelCase    ) - num_inference_steps * self.scheduler.order
					with self.progress_bar(total=_lowerCamelCase    ) as progress_bar:
						for i, t in enumerate(_lowerCamelCase    ):
							# expand the latents if we are doing classifier free guidance
							A_					:			Union[str, Any]						=						np.concatenate([latents] * 2    ) if do_classifier_free_guidance else latents

							# concat latents, mask, masked_image_latents in the channel dimension
							A_					:			Union[str, Any]						=						self.scheduler.scale_model_input(_lowerCamelCase ,       _lowerCamelCase    )
							A_					:			str						=						np.concatenate([latent_model_input, image] ,       axis=1    )

							# timestep to tensor
							A_					:			Union[str, Any]						=						np.array([t] ,       dtype=_lowerCamelCase    )

							# predict the noise residual
							A_					:			List[Any]						=						self.unet(
							    sample=_lowerCamelCase ,       timestep=_lowerCamelCase ,       encoder_hidden_states=_lowerCamelCase ,       class_labels=noise_level.astype(np.intaa    ) ,       )[0]

							# perform guidance
							if do_classifier_free_guidance:
								A_				,	A_					:			Optional[int]						=						np.split(_lowerCamelCase ,       2    )
							A_					:			List[str]						=						noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

							# compute the previous noisy sample x_t -> x_t-1
							A_					:			List[Any]						=						self.scheduler.step(
							    torch.from_numpy(_lowerCamelCase    ) ,       _lowerCamelCase ,       _lowerCamelCase ,       **_lowerCamelCase    ).prev_sample

							# call the callback, if provided
							if i == len(_lowerCamelCase    ) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
								progress_bar.update()
								if callback is not None and i % callback_steps == 0:
									callback(_lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase    )

        # 10. Post-processing
					A_					:			int						=						self.decode_latents(latents.float()    )

					# 11. Convert to PIL
					if output_type == "pil":
						A_					:			Any						=						self.numpy_to_pil(_lowerCamelCase    )

					if not return_dict:
						return (image,)

					return ImagePipelineOutput(images=_lowerCamelCase    )







				def    a_					(							self				:   Any ,       _lowerCamelCase				:   Optional[Any]    ):



					"""simple docstring"""

					A_					:			Optional[Any]						=						1 / 0.08333 * latents
					A_					:			Any						=						self.vae(latent_sample=_lowerCamelCase    )[0]
					A_					:			str						=						np.clip(image / 2 + 0.5 ,       0 ,       1    )
					A_					:			List[Any]						=						image.transpose((0, 2, 3, 1)    )
					return image







				def    a_					(							self				:   Optional[Any] ,       _lowerCamelCase				:   Union[str, List[str]] ,       _lowerCamelCase				:   Optional[Any] ,       _lowerCamelCase				:   Optional[int] ,       _lowerCamelCase				:   bool ,       _lowerCamelCase				:   Optional[str] ,       _lowerCamelCase				:   Optional[torch.FloatTensor] = None ,       _lowerCamelCase				:   Optional[torch.FloatTensor] = None ,       ):



					"""simple docstring"""

					if prompt is not None and isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
						A_					:			int						=						1
					elif prompt is not None and isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
						A_					:			Union[str, Any]						=						len(_lowerCamelCase    )
					else:
						A_					:			str						=						prompt_embeds.shape[0]

					if prompt_embeds is None:
						A_					:			int						=						self.tokenizer(
						    _lowerCamelCase ,       padding='''max_length''' ,       max_length=self.tokenizer.model_max_length ,       truncation=_lowerCamelCase ,       return_tensors='''pt''' ,       )
						A_					:			Any						=						text_inputs.input_ids
						A_					:			Optional[int]						=						self.tokenizer(_lowerCamelCase ,       padding='''longest''' ,       return_tensors='''pt'''    ).input_ids

						if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
						    _lowerCamelCase ,       _lowerCamelCase    ):
							A_					:			Dict						=						self.tokenizer.batch_decode(
							    untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]    )
							logger.warning(
							    '''The following part of your input was truncated because CLIP can only handle sequences up to'''
							    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""    )

						# no positional arguments to text_encoder
						A_					:			Any						=						self.text_encoder(
						    input_ids=text_input_ids.int().to(_lowerCamelCase    ) ,       )
						A_					:			Dict						=						prompt_embeds[0]

					A_				,	A_				,	A_					:			str						=						prompt_embeds.shape
					# duplicate text embeddings for each generation per prompt, using mps friendly method
					A_					:			str						=						prompt_embeds.repeat(1 ,       _lowerCamelCase    )
					A_					:			Optional[Any]						=						prompt_embeds.reshape(bs_embed * num_images_per_prompt ,       _lowerCamelCase ,       -1    )

					# get unconditional embeddings for classifier free guidance
					if do_classifier_free_guidance and negative_prompt_embeds is None:
						A_					:			List[str]
						if negative_prompt is None:
							A_					:			Optional[Any]						=						[''''''] * batch_size
						elif type(_lowerCamelCase    ) is not type(_lowerCamelCase    ):
							raise TypeError(
							    F"""`negative_prompt` should be the same type to `prompt`, but got {type(_lowerCamelCase    )} !="""
							    F""" {type(_lowerCamelCase    )}."""    )
						elif isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
							A_					:			Dict						=						[negative_prompt]
						elif batch_size != len(_lowerCamelCase    ):
							raise ValueError(
							    F"""`negative_prompt`: {negative_prompt} has batch size {len(_lowerCamelCase    )}, but `prompt`:"""
							    F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
							    ''' the batch size of `prompt`.'''    )
						else:
							A_					:			str						=						negative_prompt

						A_					:			Tuple						=						text_input_ids.shape[-1]
						A_					:			Optional[Any]						=						self.tokenizer(
						    _lowerCamelCase ,       padding='''max_length''' ,       max_length=_lowerCamelCase ,       truncation=_lowerCamelCase ,       return_tensors='''pt''' ,       )

						# if hasattr(uncond_input, "attention_mask"):
						#     attention_mask = uncond_input.attention_mask.to(device)
						# else:
						#     attention_mask = None

						A_					:			str						=						self.text_encoder(
						    input_ids=uncond_input.input_ids.int().to(_lowerCamelCase    ) ,       )
						A_					:			List[Any]						=						uncond_embeddings[0]

					if do_classifier_free_guidance:
						A_					:			List[str]						=						uncond_embeddings.shape[1]
						# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
						A_					:			Tuple						=						uncond_embeddings.repeat(1 ,       _lowerCamelCase    )
						A_					:			Union[str, Any]						=						uncond_embeddings.reshape(batch_size * num_images_per_prompt ,       _lowerCamelCase ,       -1    )

						# For classifier free guidance, we need to do two forward passes.
						# Here we concatenate the unconditional and text embeddings into a single batch
						# to avoid doing two forward passes
						A_					:			Tuple						=						np.concatenate([uncond_embeddings, prompt_embeds]    )

					return prompt_embeds











"""simple docstring"""

import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


_lowerCamelCase					:     Optional[int]				       =    set()
_lowerCamelCase					:     Union[str, Any]				       =    get_logger(__name__)

def 						lowercase_ (						_UpperCAmelCase = None		):




	"""simple docstring"""






	def decorator(_UpperCAmelCase		):
		global _emitted_deprecation_warnings

		if inspect.isclass(_UpperCAmelCase		):
			A_					:			Union[str, Any]						=						deprecated_class_or_function.__init__
			A_					:			int						=						deprecated_class_or_function.__name__
		else:
			A_					:			Union[str, Any]						=						deprecated_class_or_function
			A_					:			List[Any]						=						deprecated_function.__name__
			# Support deprecating __init__ class method: class name instead
			A_					:			List[Any]						=						name if name != '''__init__''' else deprecated_function.__qualname__.split('''.'''		)[-2]

		A_					:			str						=						(
		    f"""{name} is deprecated and will be removed in the next major version of datasets.""" + f""" {help_message}"""
		    if help_message
		    else ''''''
		)

		@wraps(_UpperCAmelCase		)
		def wrapper(*_UpperCAmelCase					, **_UpperCAmelCase		):
			A_					:			Any						=						hash(_UpperCAmelCase		)
			if func_hash not in _emitted_deprecation_warnings:
				warnings.warn(_UpperCAmelCase					, category=_UpperCAmelCase					, stacklevel=2		)
				_emitted_deprecation_warnings.add(_UpperCAmelCase		)
			return deprecated_function(*_UpperCAmelCase					, **_UpperCAmelCase		)

		A_					:			Any						=						'''deprecated'''

		if inspect.isclass(_UpperCAmelCase		):
			A_					:			List[Any]						=						wrapper
			return deprecated_class_or_function
		else:
			return wrapper

	return decorator

class     lowercase (      enum.EnumMeta):







				def __getattribute__(							cls				:   Any ,       _lowerCamelCase				:   List[Any]    ):



					"""simple docstring"""

					A_					:			str						=						super().__getattribute__(_lowerCamelCase    )
					if isinstance(_lowerCamelCase ,       enum.Enum    ) and obj._on_access:
						obj._on_access()
					return obj







				def __getitem__(							cls				:   Any ,       _lowerCamelCase				:   Union[str, Any]    ):



					"""simple docstring"""

					A_					:			Optional[Any]						=						super().__getitem__(_lowerCamelCase    )
					if member._on_access:
						member._on_access()
					return member







				def __call__(							cls				:   str ,       _lowerCamelCase				:   str ,       _lowerCamelCase				:   List[Any]=None ,       *, _lowerCamelCase				:   int=None ,       _lowerCamelCase				:   str=None ,       _lowerCamelCase				:   Dict=None ,       _lowerCamelCase				:   Tuple=1    ):



					"""simple docstring"""

					A_					:			Dict						=						super().__call__(_lowerCamelCase ,       _lowerCamelCase ,       module=_lowerCamelCase ,       qualname=_lowerCamelCase ,       type=_lowerCamelCase ,       start=_lowerCamelCase    )
					if isinstance(_lowerCamelCase ,       enum.Enum    ) and obj._on_access:
						obj._on_access()
					return obj

class     lowercase (      enum.Enum       ,		metaclass=__UpperCAmelCase):







				def __new__(							cls				:   Optional[Any] ,       _lowerCamelCase				:   int    ):



					"""simple docstring"""

					A_					:			Tuple						=						object.__new__(cls    )
					A_					:			Union[str, Any]						=						value
					A_					:			Union[str, Any]						=						member.deprecate
					return member







				@property
				def    a_					(							self				:   Tuple    ):



					"""simple docstring"""

					return ""







				def    a_					(							self				:   Any    ):



					"""simple docstring"""

					A_					:			Optional[int]						=						F""" {self.help_message}""" if self.help_message else ''''''
					warnings.warn(
					    F"""'{self.__objclass__.__name__}' is deprecated and will be removed in the next major version of datasets."""
					    + help_message ,       _lowerCamelCase ,       stacklevel=3 ,       )





