

"""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


_SCREAMING_SNAKE_CASE       :  Optional[int]        = getLogger(__name__)


_SCREAMING_SNAKE_CASE       :  Tuple        = 4
_SCREAMING_SNAKE_CASE       :  Dict        = 7

_SCREAMING_SNAKE_CASE       :  List[Any]        = {
    """float16""": torch.floataa,
    """float32""": torch.floataa,
}



def        _lowerCAmelCase      (						UpperCAmelCase     :							Union[str, Any]				):


					'''simple docstring'''






					if isinstance(UpperCAmelCase      ,							torch.Tensor				):
										return image
					elif isinstance(UpperCAmelCase      ,							PIL.Image.Image				):
										UpperCamelCase__		:    int         =[image]

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

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

					return image







class     __a   (      snake_case__    ):

			"""simple docstring"""

			def __init__(							self     :					List[Any]						,  lowercase_     :					OnnxRuntimeModel						,  lowercase_     :					OnnxRuntimeModel						,  lowercase_     :					Any						,  lowercase_     :					OnnxRuntimeModel						,  lowercase_     :					DDPMScheduler						,  lowercase_     :					Any						,  lowercase_     :					int = 350						,  ):
								super().__init__(
								    vae=lowercase_						,  text_encoder=lowercase_						,  tokenizer=lowercase_						,  unet=lowercase_						,  low_res_scheduler=lowercase_						,  scheduler=lowercase_						,  safety_checker=lowercase_						,  feature_extractor=lowercase_						,  watermarker=lowercase_						,  max_noise_level=lowercase_						,  )






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

								# 2. Define call parameters
								if prompt is not None and isinstance(lowercase_						,  lowercase_						):
													UpperCamelCase__		:    List[Any]         =1
								elif prompt is not None and isinstance(lowercase_						,  lowercase_						):
													UpperCamelCase__		:    Tuple         =len(lowercase_						)
								else:
													UpperCamelCase__		:    Dict         =prompt_embeds.shape[0]

								UpperCamelCase__		:    Dict         =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.
								UpperCamelCase__		:    Optional[Any]         =guidance_scale > 1.0

								# 3. Encode input prompt
								UpperCamelCase__		:    Dict         =self._encode_prompt(
								    lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  prompt_embeds=lowercase_						,  negative_prompt_embeds=lowercase_						,  )

								UpperCamelCase__		:    Dict         =ORT_TO_PT_TYPE[str(text_embeddings.dtype						)]

								# 4. Preprocess image
								UpperCamelCase__		:    Optional[int]         =preprocess(lowercase_						)
								UpperCamelCase__		:    List[str]         =image.cpu()

								# 5. set timesteps
								self.scheduler.set_timesteps(lowercase_						,  device=lowercase_						)
								UpperCamelCase__		:    str         =self.scheduler.timesteps

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

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

								# 6. Prepare latent variables
								UpperCamelCase__  ,			UpperCamelCase__		:    Optional[Any]         =image.shape[2:]
								UpperCamelCase__		:    str         =self.prepare_latents(
								    batch_size * num_images_per_prompt						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  lowercase_						,  )

								# 7. Check that sizes of image and latents match
								UpperCamelCase__		:    Union[str, Any]         =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
								UpperCamelCase__		:    Union[str, Any]         =self.prepare_extra_step_kwargs(lowercase_						,  lowercase_						)

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

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

																		# concat latents, mask, masked_image_latents in the channel dimension
																		UpperCamelCase__		:    Optional[int]         =self.scheduler.scale_model_input(lowercase_						,  lowercase_						)
																		UpperCamelCase__		:    str         =np.concatenate([latent_model_input, image]						,  axis=1						)

																		# timestep to tensor
																		UpperCamelCase__		:    List[Any]         =np.array([t]						,  dtype=lowercase_						)

																		# predict the noise residual
																		UpperCamelCase__		:    str         =self.unet(
																		    sample=lowercase_						,  timestep=lowercase_						,  encoder_hidden_states=lowercase_						,  class_labels=noise_level.astype(np.intaa						)						,  )[0]

																		# perform guidance
																		if do_classifier_free_guidance:
																							UpperCamelCase__  ,			UpperCamelCase__		:    Dict         =np.split(lowercase_						,  2						)
																		UpperCamelCase__		:    List[str]         =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

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

																		# call the callback, if provided
																		if i == len(lowercase_						) - 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(lowercase_						,  lowercase_						,  lowercase_						)

        # 10. Post-processing
								UpperCamelCase__		:    List[str]         =self.decode_latents(latents.float()						)

								# 11. Convert to PIL
								if output_type == "pil":
													UpperCamelCase__		:    Dict         =self.numpy_to_pil(lowercase_						)

								if not return_dict:
													return (image,)

								return ImagePipelineOutput(images=lowercase_						)






			def    _lowerCAmelCase			(							self     :					int						,  lowercase_     :					List[Any]						):
								UpperCamelCase__		:    List[str]         =1 / 0.0_8_3_3_3 * latents
								UpperCamelCase__		:    Optional[Any]         =self.vae(latent_sample=lowercase_						)[0]
								UpperCamelCase__		:    Dict         =np.clip(image / 2 + 0.5						,  0						,  1						)
								UpperCamelCase__		:    Optional[int]         =image.transpose((0, 2, 3, 1)						)
								return image






			def    _lowerCAmelCase			(							self     :					str						,  lowercase_     :					Union[str, List[str]]						,  lowercase_     :					List[Any]						,  lowercase_     :					Optional[int]						,  lowercase_     :					bool						,  lowercase_     :					Optional[str]						,  lowercase_     :					Optional[torch.FloatTensor] = None						,  lowercase_     :					Optional[torch.FloatTensor] = None						,  ):
								if prompt is not None and isinstance(lowercase_						,  lowercase_						):
													UpperCamelCase__		:    Tuple         =1
								elif prompt is not None and isinstance(lowercase_						,  lowercase_						):
													UpperCamelCase__		:    int         =len(lowercase_						)
								else:
													UpperCamelCase__		:    Union[str, Any]         =prompt_embeds.shape[0]

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

													if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
													    lowercase_						,  lowercase_						):
																		UpperCamelCase__		:    List[str]         =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
													UpperCamelCase__		:    List[str]         =self.text_encoder(
													    input_ids=text_input_ids.int().to(lowercase_						)						,  )
													UpperCamelCase__		:    Union[str, Any]         =prompt_embeds[0]

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

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

													UpperCamelCase__		:    Any         =text_input_ids.shape[-1]
													UpperCamelCase__		:    List[str]         =self.tokenizer(
													    lowercase_						,  padding='''max_length'''						,  max_length=lowercase_						,  truncation=lowercase_						,  return_tensors='''pt'''						,  )

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

													UpperCamelCase__		:    int         =self.text_encoder(
													    input_ids=uncond_input.input_ids.int().to(lowercase_						)						,  )
													UpperCamelCase__		:    Optional[Any]         =uncond_embeddings[0]

								if do_classifier_free_guidance:
													UpperCamelCase__		:    Optional[Any]         =uncond_embeddings.shape[1]
													# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
													UpperCamelCase__		:    List[str]         =uncond_embeddings.repeat(1						,  lowercase_						)
													UpperCamelCase__		:    Optional[Any]         =uncond_embeddings.reshape(batch_size * num_images_per_prompt						,  lowercase_						,  -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
													UpperCamelCase__		:    List[Any]         =np.concatenate([uncond_embeddings, prompt_embeds]						)

								return prompt_embeds





"""simple docstring"""





import unittest

from transformers.image_processing_utils import get_size_dict

class     __a   (      unittest.TestCase    ):

			"""simple docstring"""

			def    _lowerCAmelCase			(							self     :					Dict						):
								# Test a dict with the wrong keys raises an error
								UpperCamelCase__		:    str         ={'''wrong_key''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								UpperCamelCase__		:    Any         ={'''height''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								UpperCamelCase__		:    List[str]         ={'''width''': 224, '''shortest_edge''': 224}
								with self.assertRaises(lowercase_						):
													get_size_dict(lowercase_						)

								# Test a dict with the correct keys is returned as is
								UpperCamelCase__		:    int         ={'''height''': 224, '''width''': 224}
								UpperCamelCase__		:    str         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  lowercase_						)

								UpperCamelCase__		:    List[Any]         ={'''shortest_edge''': 224}
								UpperCamelCase__		:    List[str]         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224}						)

								UpperCamelCase__		:    List[Any]         ={'''longest_edge''': 224, '''shortest_edge''': 224}
								UpperCamelCase__		:    Tuple         =get_size_dict(lowercase_						)
								self.assertEqual(lowercase_						,  {'''longest_edge''': 224, '''shortest_edge''': 224}						)

								# Test a single int value which  represents (size, size)
								UpperCamelCase__		:    Optional[int]         =get_size_dict(224						)
								self.assertEqual(lowercase_						,  {'''height''': 224, '''width''': 224}						)

								# Test a single int value which represents the shortest edge
								UpperCamelCase__		:    str         =get_size_dict(224						,  default_to_square=lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224}						)

								# Test a tuple of ints which represents (height, width)
								UpperCamelCase__		:    List[str]         =get_size_dict((150, 200)						)
								self.assertEqual(lowercase_						,  {'''height''': 150, '''width''': 200}						)

								# Test a tuple of ints which represents (width, height)
								UpperCamelCase__		:    Optional[int]         =get_size_dict((150, 200)						,  height_width_order=lowercase_						)
								self.assertEqual(lowercase_						,  {'''height''': 200, '''width''': 150}						)

								# Test an int representing the shortest edge and max_size which represents the longest edge
								UpperCamelCase__		:    int         =get_size_dict(224						,  max_size=256						,  default_to_square=lowercase_						)
								self.assertEqual(lowercase_						,  {'''shortest_edge''': 224, '''longest_edge''': 256}						)

								# Test int with default_to_square=True and max_size fails
								with self.assertRaises(lowercase_						):
													get_size_dict(224						,  max_size=256						,  default_to_square=lowercase_						)


