

"""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							:	Optional[Any]										=			4
_SCREAMING_SNAKE_CASE							:	Dict										=			7

_SCREAMING_SNAKE_CASE							:	int										=			{
    """float16""": torch.floataa,
    """float32""": torch.floataa,
}



def 							_lowerCAmelCase   (    UpperCAmelCase  :				int					):


					'''simple docstring'''






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

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

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

					return image







class      __a (   snake_case__     ):

			"""simple docstring"""

			def __init__(				self  :       List[str]    ,	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  :       Tuple    ,	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[str]								=1
								elif prompt is not None and isinstance(lowercase_    ,	lowercase_    ):
													UpperCamelCase__		:     Tuple								=len(lowercase_    )
								else:
													UpperCamelCase__		:     Optional[Any]								=prompt_embeds.shape[0]

								UpperCamelCase__		:     int								=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__		:     Any								=guidance_scale > 1.0

								# 3. Encode input prompt
								UpperCamelCase__		:     List[str]								=self._encode_prompt(
								    lowercase_    ,	lowercase_    ,	lowercase_    ,	lowercase_    ,	lowercase_    ,	prompt_embeds=lowercase_    ,	negative_prompt_embeds=lowercase_    ,	)

								UpperCamelCase__		:     Union[str, Any]								=ORT_TO_PT_TYPE[str(text_embeddings.dtype    )]

								# 4. Preprocess image
								UpperCamelCase__		:     Optional[Any]								=preprocess(lowercase_    )
								UpperCamelCase__		:     Dict								=image.cpu()

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

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

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

								# 6. Prepare latent variables
								UpperCamelCase__	,      UpperCamelCase__		:     Tuple								=image.shape[2:]
								UpperCamelCase__		:     List[Any]								=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__		:     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__		:     Any								=self.prepare_extra_step_kwargs(lowercase_    ,	lowercase_    )

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

								# 9. Denoising loop
								UpperCamelCase__		:     Dict								=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__		:     List[Any]								=np.concatenate([latents] * 2    ) if do_classifier_free_guidance else latents

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

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

																		# predict the noise residual
																		UpperCamelCase__		:     List[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__		:     Dict								=noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

																		# compute the previous noisy sample x_t -> x_t-1
																		UpperCamelCase__		:     Dict								=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__		:     int								=self.decode_latents(latents.float()    )

								# 11. Convert to PIL
								if output_type == "pil":
													UpperCamelCase__		:     List[Any]								=self.numpy_to_pil(lowercase_    )

								if not return_dict:
													return (image,)

								return ImagePipelineOutput(images=lowercase_    )






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






			def  _lowerCAmelCase      (				self  :       Dict    ,	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__		:     List[str]								=1
								elif prompt is not None and isinstance(lowercase_    ,	lowercase_    ):
													UpperCamelCase__		:     Dict								=len(lowercase_    )
								else:
													UpperCamelCase__		:     str								=prompt_embeds.shape[0]

								if prompt_embeds is None:
													UpperCamelCase__		:     Optional[Any]								=self.tokenizer(
													    lowercase_    ,	padding='''max_length'''    ,	max_length=self.tokenizer.model_max_length    ,	truncation=lowercase_    ,	return_tensors='''pt'''    ,	)
													UpperCamelCase__		:     int								=text_inputs.input_ids
													UpperCamelCase__		:     Any								=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__		:     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__		:     Tuple								=self.text_encoder(
													    input_ids=text_input_ids.int().to(lowercase_    )    ,	)
													UpperCamelCase__		:     Dict								=prompt_embeds[0]

								UpperCamelCase__	,      UpperCamelCase__	,      UpperCamelCase__		:     Dict								=prompt_embeds.shape
								# duplicate text embeddings for each generation per prompt, using mps friendly method
								UpperCamelCase__		:     Dict								=prompt_embeds.repeat(1    ,	lowercase_    )
								UpperCamelCase__		:     int								=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[Any]								=[''''''] * 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__		:     int								=[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__		:     str								=negative_prompt

													UpperCamelCase__		:     Dict								=text_input_ids.shape[-1]
													UpperCamelCase__		:     Any								=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__		:     Optional[int]								=self.text_encoder(
													    input_ids=uncond_input.input_ids.int().to(lowercase_    )    ,	)
													UpperCamelCase__		:     Tuple								=uncond_embeddings[0]

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

								return prompt_embeds





"""simple docstring"""





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mpnet import MPNetTokenizer


_SCREAMING_SNAKE_CASE							:	Union[str, Any]										=			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE							:	Union[str, Any]										=			{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

_SCREAMING_SNAKE_CASE							:	List[Any]										=			{
    """vocab_file""": {
        """microsoft/mpnet-base""": """https://huggingface.co/microsoft/mpnet-base/resolve/main/vocab.txt""",
    },
    """tokenizer_file""": {
        """microsoft/mpnet-base""": """https://huggingface.co/microsoft/mpnet-base/resolve/main/tokenizer.json""",
    },
}

_SCREAMING_SNAKE_CASE							:	List[Any]										=			{
    """microsoft/mpnet-base""": 5_1_2,
}

_SCREAMING_SNAKE_CASE							:	Optional[int]										=			{
    """microsoft/mpnet-base""": {"""do_lower_case""": True},
}

class      __a (   snake_case__     ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_      =    VOCAB_FILES_NAMES
			SCREAMING_SNAKE_CASE_      =    PRETRAINED_VOCAB_FILES_MAP
			SCREAMING_SNAKE_CASE_      =    PRETRAINED_INIT_CONFIGURATION
			SCREAMING_SNAKE_CASE_      =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			SCREAMING_SNAKE_CASE_      =    MPNetTokenizer
			SCREAMING_SNAKE_CASE_      =    ['input_ids', 'attention_mask']






			def __init__(				self  :       List[str]    ,	lowercase_  :       List[Any]=None    ,	lowercase_  :       Optional[int]=None    ,	lowercase_  :       Optional[int]=True    ,	lowercase_  :       str="<s>"    ,	lowercase_  :       str="</s>"    ,	lowercase_  :       List[Any]="</s>"    ,	lowercase_  :       Tuple="<s>"    ,	lowercase_  :       Any="[UNK]"    ,	lowercase_  :       Dict="<pad>"    ,	lowercase_  :       Optional[Any]="<mask>"    ,	lowercase_  :       List[str]=True    ,	lowercase_  :       Optional[Any]=None    ,	**lowercase_  :       Dict    ,	):
								super().__init__(
								    lowercase_    ,	tokenizer_file=lowercase_    ,	do_lower_case=lowercase_    ,	bos_token=lowercase_    ,	eos_token=lowercase_    ,	sep_token=lowercase_    ,	cls_token=lowercase_    ,	unk_token=lowercase_    ,	pad_token=lowercase_    ,	mask_token=lowercase_    ,	tokenize_chinese_chars=lowercase_    ,	strip_accents=lowercase_    ,	**lowercase_    ,	)

								UpperCamelCase__		:     List[str]								=json.loads(self.backend_tokenizer.normalizer.__getstate__()    )
								if (
								    pre_tok_state.get('''lowercase'''    ,	lowercase_    ) != do_lower_case
								    or pre_tok_state.get('''strip_accents'''    ,	lowercase_    ) != strip_accents
								):
													UpperCamelCase__		:     int								=getattr(lowercase_    ,	pre_tok_state.pop('''type'''    )    )
													UpperCamelCase__		:     List[Any]								=do_lower_case
													UpperCamelCase__		:     Optional[Any]								=strip_accents
													UpperCamelCase__		:     Optional[int]								=pre_tok_class(**lowercase_    )

								UpperCamelCase__		:     Tuple								=do_lower_case






			@property
			def  _lowerCAmelCase      (				self  :       List[str]    ):
								if self._mask_token is None:
													if self.verbose:
																		logger.error('''Using mask_token, but it is not set yet.'''    )
													return None
								return str(self._mask_token    )






			@mask_token.setter
			def  _lowerCAmelCase      (				self  :       int    ,	lowercase_  :       str    ):
								UpperCamelCase__		:     int								=AddedToken(lowercase_    ,	lstrip=lowercase_    ,	rstrip=lowercase_    ) if isinstance(lowercase_    ,	lowercase_    ) else value
								UpperCamelCase__		:     str								=value






			def  _lowerCAmelCase      (				self  :       Tuple    ,	lowercase_  :       Any    ,	lowercase_  :       Tuple=None    ):
								UpperCamelCase__		:     int								=[self.bos_token_id] + token_ids_a + [self.eos_token_id]
								if token_ids_a is None:
													return output

								return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]






			def  _lowerCAmelCase      (				self  :       List[str]    ,	lowercase_  :       List[int]    ,	lowercase_  :       Optional[List[int]] = None    ):
								UpperCamelCase__		:     str								=[self.sep_token_id]
								UpperCamelCase__		:     List[str]								=[self.cls_token_id]

								if token_ids_a is None:
													return len(cls + token_ids_a + sep    ) * [0]
								return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]






			def  _lowerCAmelCase      (				self  :       str    ,	lowercase_  :       str    ,	lowercase_  :       Optional[str] = None    ):
								UpperCamelCase__		:     List[Any]								=self._tokenizer.model.save(lowercase_    ,	name=lowercase_    )
								return tuple(lowercase_    )


