






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


__snake_case     :     Union[str, Any]       =  getLogger(__name__)


__snake_case     :     Dict       =  4
__snake_case     :     Tuple       =  7

__snake_case     :     Dict       =  {
    """float16""": torch.floataa,
    """float32""": torch.floataa,
}







def 						_UpperCamelCase (     UpperCamelCase_							:       str		)	-> Optional[int]:

						"""simple docstring"""



						if isinstance(a_     ,							torch.Tensor		):
												return image
						elif isinstance(a_     ,							PIL.Image.Image		):
												lowerCAmelCase__         =    [image]

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

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

						return image


class      __SCREAMING_SNAKE_CASE       ( __UpperCAmelCase):






						def __init__(						self  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase = 3_50  ,    ):






												"""simple docstring"""
												super().__init__(
												    vae=UpperCAmelCase_  ,    text_encoder=UpperCAmelCase_  ,    tokenizer=UpperCAmelCase_  ,    unet=UpperCAmelCase_  ,    low_res_scheduler=UpperCAmelCase_  ,    scheduler=UpperCAmelCase_  ,    safety_checker=UpperCAmelCase_  ,    feature_extractor=UpperCAmelCase_  ,    watermarker=UpperCAmelCase_  ,    max_noise_level=UpperCAmelCase_  ,    )






						def __call__(						self  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase = 75  ,    _UpperCamelCase = 9.0  ,    _UpperCamelCase = 20  ,    _UpperCamelCase = None  ,    _UpperCamelCase = 1  ,    _UpperCamelCase = 0.0  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = "pil"  ,    _UpperCamelCase = True  ,    _UpperCamelCase = None  ,    _UpperCamelCase = 1  ,    ):






												"""simple docstring"""
												self.check_inputs(UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_ )

												# 2. Define call parameters
												if prompt is not None and isinstance(UpperCAmelCase_  ,    UpperCAmelCase_ ):
																		lowerCAmelCase__         =    1
												elif prompt is not None and isinstance(UpperCAmelCase_  ,    UpperCAmelCase_ ):
																		lowerCAmelCase__         =    len(UpperCAmelCase_ )
												else:
																		lowerCAmelCase__         =    prompt_embeds.shape[0]

												lowerCAmelCase__         =    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.
												lowerCAmelCase__         =    guidance_scale > 1.0

												# 3. Encode input prompt
												lowerCAmelCase__         =    self._encode_prompt(
												    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    prompt_embeds=UpperCAmelCase_  ,    negative_prompt_embeds=UpperCAmelCase_  ,    )

												lowerCAmelCase__         =    ORT_TO_PT_TYPE[str(text_embeddings.dtype )]

												# 4. Preprocess image
												lowerCAmelCase__         =    preprocess(UpperCAmelCase_ )
												lowerCAmelCase__         =    image.cpu()

												# 5. set timesteps
												self.scheduler.set_timesteps(UpperCAmelCase_  ,    device=UpperCAmelCase_ )
												lowerCAmelCase__         =    self.scheduler.timesteps

												# 5. Add noise to image
												lowerCAmelCase__         =    torch.tensor([noise_level]  ,    dtype=torch.long  ,    device=UpperCAmelCase_ )
												lowerCAmelCase__         =    torch.randn(image.shape  ,    generator=UpperCAmelCase_  ,    device=UpperCAmelCase_  ,    dtype=UpperCAmelCase_ )
												lowerCAmelCase__         =    self.low_res_scheduler.add_noise(UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_ )

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

												# 6. Prepare latent variables
												lowerCAmelCase__         =    image.shape[2:]
												lowerCAmelCase__         =    self.prepare_latents(
												    batch_size * num_images_per_prompt  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    )

												# 7. Check that sizes of image and latents match
												lowerCAmelCase__         =    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
												lowerCAmelCase__         =    self.prepare_extra_step_kwargs(UpperCAmelCase_  ,    UpperCAmelCase_ )

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

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

																								# concat latents, mask, masked_image_latents in the channel dimension
																								lowerCAmelCase__         =    self.scheduler.scale_model_input(UpperCAmelCase_  ,    UpperCAmelCase_ )
																								lowerCAmelCase__         =    np.concatenate([latent_model_input, image]  ,    axis=1 )

																								# timestep to tensor
																								lowerCAmelCase__         =    np.array([t]  ,    dtype=UpperCAmelCase_ )

																								# predict the noise residual
																								lowerCAmelCase__         =    self.unet(
																								    sample=UpperCAmelCase_  ,    timestep=UpperCAmelCase_  ,    encoder_hidden_states=UpperCAmelCase_  ,    class_labels=noise_level.astype(np.intaa )  ,    )[0]

																								# perform guidance
																								if do_classifier_free_guidance:
																														lowerCAmelCase__         =    np.split(UpperCAmelCase_  ,    2 )
																								lowerCAmelCase__         =    noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

																								# compute the previous noisy sample x_t -> x_t-1
																								lowerCAmelCase__         =    self.scheduler.step(
																								    torch.from_numpy(UpperCAmelCase_ )  ,    UpperCAmelCase_  ,    UpperCAmelCase_  ,    **UpperCAmelCase_ ).prev_sample

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

        # 10. Post-processing
												lowerCAmelCase__         =    self.decode_latents(latents.float() )

												# 11. Convert to PIL
												if output_type == "pil":
																		lowerCAmelCase__         =    self.numpy_to_pil(UpperCAmelCase_ )

												if not return_dict:
																		return (image,)

												return ImagePipelineOutput(images=UpperCAmelCase_ )






						def    UpperCamelCase__   (						self  ,    _UpperCamelCase ):






												"""simple docstring"""
												lowerCAmelCase__         =    1 / 0.0_83_33 * latents
												lowerCAmelCase__         =    self.vae(latent_sample=UpperCAmelCase_ )[0]
												lowerCAmelCase__         =    np.clip(image / 2 + 0.5  ,    0  ,    1 )
												lowerCAmelCase__         =    image.transpose((0, 2, 3, 1) )
												return image







						def    UpperCamelCase__   (						self  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    ):






												"""simple docstring"""
												if prompt is not None and isinstance(UpperCAmelCase_  ,    UpperCAmelCase_ ):
																		lowerCAmelCase__         =    1
												elif prompt is not None and isinstance(UpperCAmelCase_  ,    UpperCAmelCase_ ):
																		lowerCAmelCase__         =    len(UpperCAmelCase_ )
												else:
																		lowerCAmelCase__         =    prompt_embeds.shape[0]

												if prompt_embeds is None:
																		lowerCAmelCase__         =    self.tokenizer(
																		    UpperCAmelCase_  ,    padding='max_length'  ,    max_length=self.tokenizer.model_max_length  ,    truncation=UpperCAmelCase_  ,    return_tensors='pt'  ,    )
																		lowerCAmelCase__         =    text_inputs.input_ids
																		lowerCAmelCase__         =    self.tokenizer(UpperCAmelCase_  ,    padding='longest'  ,    return_tensors='pt' ).input_ids

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

												lowerCAmelCase__         =    prompt_embeds.shape
												# duplicate text embeddings for each generation per prompt, using mps friendly method
												lowerCAmelCase__         =    prompt_embeds.repeat(1  ,    UpperCAmelCase_ )
												lowerCAmelCase__         =    prompt_embeds.reshape(bs_embed * num_images_per_prompt  ,    UpperCAmelCase_  ,    -1 )

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

																		lowerCAmelCase__         =    text_input_ids.shape[-1]
																		lowerCAmelCase__         =    self.tokenizer(
																		    UpperCAmelCase_  ,    padding='max_length'  ,    max_length=UpperCAmelCase_  ,    truncation=UpperCAmelCase_  ,    return_tensors='pt'  ,    )

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

																		lowerCAmelCase__         =    self.text_encoder(
																		    input_ids=uncond_input.input_ids.int().to(UpperCAmelCase_ )  ,    )
																		lowerCAmelCase__         =    uncond_embeddings[0]

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

												return prompt_embeds







"""simple docstring"""

from __future__ import annotations

from queue import Queue
def 						UpperCAmelCase   (						a_,		a_     ):





		'''simple docstring'''


		a ^= b
		b ^= a
		a ^= b
		return a, b
def 						UpperCAmelCase   (						a_,		a_     ):





		'''simple docstring'''


		lowerCamelCase	:     int            =       1
		while (1 << j) < max_node:
				for i in range(1,		max_node + 1     ):
						lowerCamelCase	:     Tuple            =       parent[j - 1][parent[j - 1][i]]
				j += 1
		return parent
def 						UpperCAmelCase   (						a_,		a_,		a_,		a_     ):





		'''simple docstring'''


		if level[u] < level[v]:
				lowerCamelCase      ,       lowerCamelCase	:     List[Any]            =       swap(a_,		a_     )
		# making depth of u same as depth of v
		for i in range(18,		-1,		-1     ):
				if level[u] - (1 << i) >= level[v]:
						lowerCamelCase	:     int            =       parent[i][u]
    # at the same depth if u==v that mean lca is found
		if u == v:
				return u
		# moving both nodes upwards till lca in found
		for i in range(18,		-1,		-1     ):
				if parent[i][u] not in [0, parent[i][v]]:
						lowerCamelCase      ,       lowerCamelCase	:     str            =       parent[i][u], parent[i][v]
    # returning longest common ancestor of u,v
		return parent[0][u]
def 						UpperCAmelCase   (						a_,		a_,		a_,		a_,		a_ = 1,		):





		'''simple docstring'''


		lowerCamelCase	:     Any            =       0
		lowerCamelCase	:     Queue[int]            =       Queue(maxsize=a_     )
		q.put(a_     )
		while q.qsize() != 0:
				lowerCamelCase	:     Tuple            =       q.get()
				for v in graph[u]:
						if level[v] == -1:
								lowerCamelCase	:     Optional[Any]            =       level[u] + 1
								q.put(a_     )
								lowerCamelCase	:     str            =       u
		return level, parent
def 						UpperCAmelCase   (						):





		'''simple docstring'''


		lowerCamelCase	:     Any            =       13
		# initializing with 0
		lowerCamelCase	:     Dict            =       [[0 for _ in range(max_node + 10     )] for _ in range(20     )]
		# initializing with -1 which means every node is unvisited
		lowerCamelCase	:     List[Any]            =       [-1 for _ in range(max_node + 10     )]
		lowerCamelCase	:     dict[int, list[int]]            =       {
		    1: [2, 3, 4],
		    2: [5],
		    3: [6, 7],
		    4: [8],
		    5: [9, 10],
		    6: [11],
		    7: [],
		    8: [12, 13],
		    9: [],
		    10: [],
		    11: [],
		    12: [],
		    13: [],
		}
		lowerCamelCase      ,       lowerCamelCase	:     Dict            =       breadth_first_search(a_,		a_,		a_,		a_,		1     )
		lowerCamelCase	:     List[Any]            =       create_sparse(a_,		a_     )
		print('LCA of node 1 and 3 is: ',		lowest_common_ancestor(1,		3,		a_,		a_     )     )
		print('LCA of node 5 and 6 is: ',		lowest_common_ancestor(5,		6,		a_,		a_     )     )
		print('LCA of node 7 and 11 is: ',		lowest_common_ancestor(7,		11,		a_,		a_     )     )
		print('LCA of node 6 and 7 is: ',		lowest_common_ancestor(6,		7,		a_,		a_     )     )
		print('LCA of node 4 and 12 is: ',		lowest_common_ancestor(4,		12,		a_,		a_     )     )
		print('LCA of node 8 and 8 is: ',		lowest_common_ancestor(8,		8,		a_,		a_     )     )


if __name__ == "__main__":
					main()






