

import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference



class    _a						(__magic_name__		,       unittest.TestCase    ):


					'''simple docstring'''






					UpperCAmelCase__:       Any  							=	ShapEImgaImgPipeline
					UpperCAmelCase__:       Optional[Any]  							=	['''image''']
					UpperCAmelCase__:       int  							=	['''image''']
					UpperCAmelCase__:       Tuple  							=	[
					    '''num_images_per_prompt''',
					    '''num_inference_steps''',
					    '''generator''',
					    '''latents''',
					    '''guidance_scale''',
					    '''frame_size''',
					    '''output_type''',
					    '''return_dict''',
					]
					UpperCAmelCase__:       Optional[Any]  							=	False






					@property
					def   __A      (			self      ):
						return 32






					@property
					def   __A      (			self      ):
						return 32






					@property
					def   __A      (			self      ):
						return self.time_input_dim * 4






					@property
					def   __A      (			self      ):
						return 8






					@property
					def   __A      (			self      ):
						torch.manual_seed(0      )
						A__							:   str					       =		CLIPVisionConfig(
						    hidden_size=self.text_embedder_hidden_size   ,	image_size=64   ,	projection_dim=self.text_embedder_hidden_size   ,	intermediate_size=37   ,	num_attention_heads=4   ,	num_channels=3   ,	num_hidden_layers=5   ,	patch_size=1   ,	)

						A__							:   Dict					       =		CLIPVisionModel(A__      )
						return model






					@property
					def   __A      (			self      ):
						A__							:   Optional[Any]					       =		CLIPImageProcessor(
						    crop_size=224   ,	do_center_crop=A__   ,	do_normalize=A__   ,	do_resize=A__   ,	image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]   ,	image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]   ,	resample=3   ,	size=224   ,	)

						return image_processor






					@property
					def   __A      (			self      ):
						torch.manual_seed(0      )

						A__							:   List[Any]					       =		{
						    """num_attention_heads""": 2,
						    """attention_head_dim""": 16,
						    """embedding_dim""": self.time_input_dim,
						    """num_embeddings""": 32,
						    """embedding_proj_dim""": self.text_embedder_hidden_size,
						    """time_embed_dim""": self.time_embed_dim,
						    """num_layers""": 1,
						    """clip_embed_dim""": self.time_input_dim * 2,
						    """additional_embeddings""": 0,
						    """time_embed_act_fn""": """gelu""",
						    """norm_in_type""": """layer""",
						    """embedding_proj_norm_type""": """layer""",
						    """encoder_hid_proj_type""": None,
						    """added_emb_type""": None,
						}

						A__							:   Optional[Any]					       =		PriorTransformer(**A__      )
						return model






					@property
					def   __A      (			self      ):
						torch.manual_seed(0      )

						A__							:   Optional[Any]					       =		{
						    """param_shapes""": (
						        (self.renderer_dim, 93),
						        (self.renderer_dim, 8),
						        (self.renderer_dim, 8),
						        (self.renderer_dim, 8),
						    ),
						    """d_latent""": self.time_input_dim,
						    """d_hidden""": self.renderer_dim,
						    """n_output""": 12,
						    """background""": (
						        0.1,
						        0.1,
						        0.1,
						    ),
						}
						A__							:   List[str]					       =		ShapERenderer(**A__      )
						return model






					def   __A      (			self      ):
						A__							:   Optional[Any]					       =		self.dummy_prior
						A__							:   List[str]					       =		self.dummy_image_encoder
						A__							:   Any					       =		self.dummy_image_processor
						A__							:   str					       =		self.dummy_renderer

						A__							:   List[Any]					       =		HeunDiscreteScheduler(
						    beta_schedule="""exp"""   ,	num_train_timesteps=1024   ,	prediction_type="""sample"""   ,	use_karras_sigmas=A__   ,	clip_sample=A__   ,	clip_sample_range=1.0   ,	)
						A__							:   List[str]					       =		{
						    """prior""": prior,
						    """image_encoder""": image_encoder,
						    """image_processor""": image_processor,
						    """renderer""": renderer,
						    """scheduler""": scheduler,
						}

						return components






					def   __A      (			self   ,	A__   ,	A__=0      ):
						A__							:   List[Any]					       =		floats_tensor((1, 3, 64, 64)   ,	rng=random.Random(A__      )      ).to(A__      )

						if str(A__      ).startswith("""mps"""      ):
							A__							:   Union[str, Any]					       =		torch.manual_seed(A__      )
						else:
							A__							:   Dict					       =		torch.Generator(device=A__      ).manual_seed(A__      )
						A__							:   int					       =		{
						    """image""": input_image,
						    """generator""": generator,
						    """num_inference_steps""": 1,
						    """frame_size""": 32,
						    """output_type""": """np""",
						}
						return inputs






					def   __A      (			self      ):
						A__							:   List[str]					       =		"""cpu"""

						A__							:   List[str]					       =		self.get_dummy_components()

						A__							:   Tuple					       =		self.pipeline_class(**A__      )
						A__							:   int					       =		pipe.to(A__      )

						pipe.set_progress_bar_config(disable=A__      )

						A__							:   int					       =		pipe(**self.get_dummy_inputs(A__      )      )
						A__							:   List[str]					       =		output.images[0]
						A__							:   Union[str, Any]					       =		image[0, -3:, -3:, -1]

						assert image.shape == (20, 32, 32, 3)

						A__							:   Tuple					       =		np.array(
						    [
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						    ]      )

						assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2






					def   __A      (			self      ):
						# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
						self._test_inference_batch_consistent(batch_sizes=[1, 2]      )






					def   __A      (			self      ):
						A__							:   Optional[Any]					       =		torch_device == """cpu"""
						A__							:   int					       =		True
						self._test_inference_batch_single_identical(
						    batch_size=2   ,	test_max_difference=A__   ,	relax_max_difference=A__   ,	)






					def   __A      (			self      ):
						A__							:   Tuple					       =		self.get_dummy_components()
						A__							:   Optional[Any]					       =		self.pipeline_class(**A__      )
						A__							:   str					       =		pipe.to(A__      )
						pipe.set_progress_bar_config(disable=A__      )

						A__							:   Optional[Any]					       =		1
						A__							:   Dict					       =		2

						A__							:   Any					       =		self.get_dummy_inputs(A__      )

						for key in inputs.keys():
							if key in self.batch_params:
								A__							:   Tuple					       =		batch_size * [inputs[key]]

						A__							:   List[Any]					       =		pipe(**A__   ,	num_images_per_prompt=A__      )[0]

						assert images.shape[0] == batch_size * num_images_per_prompt



@slow
@require_torch_gpu
class    _a						(unittest.TestCase    ):


					'''simple docstring'''






					def   __A      (			self      ):
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()






					def   __A      (			self      ):
						A__							:   Dict					       =		load_image(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png"""      )
						A__							:   Optional[Any]					       =		load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/shap_e/test_shap_e_img2img_out.npy"""      )
						A__							:   Union[str, Any]					       =		ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img"""      )
						A__							:   Optional[int]					       =		pipe.to(A__      )
						pipe.set_progress_bar_config(disable=A__      )

						A__							:   Optional[Any]					       =		torch.Generator(device=A__      ).manual_seed(0      )

						A__							:   Optional[int]					       =		pipe(
						    A__   ,	generator=A__   ,	guidance_scale=3.0   ,	num_inference_steps=64   ,	frame_size=64   ,	output_type="""np"""   ,	).images[0]

						assert images.shape == (20, 64, 64, 3)

						assert_mean_pixel_difference(A__   ,	A__      )






import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


A_	:			int  	=      logging.get_logger(__name__)  # pylint: disable=invalid-name



class    _a						(__magic_name__    ):


					'''simple docstring'''






					def __init__(			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__   ,	):
						super().__init__()

						if safety_checker is None:
							logger.warning(
							    F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
							    """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
							    """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
							    """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
							    """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
							    """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""      )

						self.register_modules(
						    speech_model=A__   ,	speech_processor=A__   ,	vae=A__   ,	text_encoder=A__   ,	tokenizer=A__   ,	unet=A__   ,	scheduler=A__   ,	feature_extractor=A__   ,	)






					def   __A      (			self   ,	A__ = "auto"      ):
						if slice_size == "auto":
							A__							:   Optional[Any]					       =		self.unet.config.attention_head_dim // 2
						self.unet.set_attention_slice(A__      )






					def   __A      (			self      ):
						self.enable_attention_slicing(A__      )






					@torch.no_grad()
					def __call__(			self   ,	A__   ,	A__=1_6000   ,	A__ = 512   ,	A__ = 512   ,	A__ = 50   ,	A__ = 7.5   ,	A__ = None   ,	A__ = 1   ,	A__ = 0.0   ,	A__ = None   ,	A__ = None   ,	A__ = "pil"   ,	A__ = True   ,	A__ = None   ,	A__ = 1   ,	**A__   ,	):
						A__							:   Any					       =		self.speech_processor.feature_extractor(
						    A__   ,	return_tensors="""pt"""   ,	sampling_rate=A__      ).input_features.to(self.device      )
						A__							:   Optional[Any]					       =		self.speech_model.generate(A__   ,	max_length=48_0000      )

						A__							:   Union[str, Any]					       =		self.speech_processor.tokenizer.batch_decode(A__   ,	skip_special_tokens=A__   ,	normalize=A__      )[
						    0
						]

						if isinstance(A__   ,	A__      ):
							A__							:   Dict					       =		1
						elif isinstance(A__   ,	A__      ):
							A__							:   Optional[int]					       =		len(A__      )
						else:
							raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(A__      )}"""      )

						if height % 8 != 0 or width % 8 != 0:
							raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""      )

						if (callback_steps is None) or (
						    callback_steps is not None and (not isinstance(A__   ,	A__      ) or callback_steps <= 0)
						):
							raise ValueError(
							    F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
							    F""" {type(A__      )}."""      )

						# get prompt text embeddings
						A__							:   Optional[int]					       =		self.tokenizer(
						    A__   ,	padding="""max_length"""   ,	max_length=self.tokenizer.model_max_length   ,	return_tensors="""pt"""   ,	)
						A__							:   Any					       =		text_inputs.input_ids

						if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
							A__							:   str					       =		self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]      )
							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}"""      )
							A__							:   Dict					       =		text_input_ids[:, : self.tokenizer.model_max_length]
						A__							:   int					       =		self.text_encoder(text_input_ids.to(self.device      )      )[0]

						# duplicate text embeddings for each generation per prompt, using mps friendly method
						A__       ,       A__       ,       A__							:   List[str]					       =		text_embeddings.shape
						A__							:   Dict					       =		text_embeddings.repeat(1   ,	A__   ,	1      )
						A__							:   Union[str, Any]					       =		text_embeddings.view(bs_embed * num_images_per_prompt   ,	A__   ,	-1      )

						# 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__							:   int					       =		guidance_scale > 1.0
						# get unconditional embeddings for classifier free guidance
						if do_classifier_free_guidance:
							A__							:   List[str]
							if negative_prompt is None:
								A__							:   Union[str, Any]					       =		[""""""] * batch_size
							elif type(A__      ) is not type(A__      ):
								raise TypeError(
								    F"""`negative_prompt` should be the same type to `prompt`, but got {type(A__      )} !="""
								    F""" {type(A__      )}."""      )
							elif isinstance(A__   ,	A__      ):
								A__							:   Union[str, Any]					       =		[negative_prompt]
							elif batch_size != len(A__      ):
								raise ValueError(
								    F"""`negative_prompt`: {negative_prompt} has batch size {len(A__      )}, but `prompt`:"""
								    F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
								    """ the batch size of `prompt`."""      )
							else:
								A__							:   int					       =		negative_prompt

							A__							:   Union[str, Any]					       =		text_input_ids.shape[-1]
							A__							:   int					       =		self.tokenizer(
							    A__   ,	padding="""max_length"""   ,	max_length=A__   ,	truncation=A__   ,	return_tensors="""pt"""   ,	)
							A__							:   Any					       =		self.text_encoder(uncond_input.input_ids.to(self.device      )      )[0]

							# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
							A__							:   List[Any]					       =		uncond_embeddings.shape[1]
							A__							:   Any					       =		uncond_embeddings.repeat(1   ,	A__   ,	1      )
							A__							:   Optional[Any]					       =		uncond_embeddings.view(batch_size * num_images_per_prompt   ,	A__   ,	-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__							:   Any					       =		torch.cat([uncond_embeddings, text_embeddings]      )

						# get the initial random noise unless the user supplied it

						# Unlike in other pipelines, latents need to be generated in the target device
						# for 1-to-1 results reproducibility with the CompVis implementation.
						# However this currently doesn't work in `mps`.
						A__							:   List[Any]					       =		(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
						A__							:   Dict					       =		text_embeddings.dtype
						if latents is None:
							if self.device.type == "mps":
								# randn does not exist on mps
								A__							:   Optional[Any]					       =		torch.randn(A__   ,	generator=A__   ,	device="""cpu"""   ,	dtype=A__      ).to(
								    self.device      )
							else:
								A__							:   str					       =		torch.randn(A__   ,	generator=A__   ,	device=self.device   ,	dtype=A__      )
						else:
							if latents.shape != latents_shape:
								raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""      )
							A__							:   Any					       =		latents.to(self.device      )

						# set timesteps
						self.scheduler.set_timesteps(A__      )

						# Some schedulers like PNDM have timesteps as arrays
						# It's more optimized to move all timesteps to correct device beforehand
						A__							:   List[str]					       =		self.scheduler.timesteps.to(self.device      )

						# scale the initial noise by the standard deviation required by the scheduler
						A__							:   Tuple					       =		latents * self.scheduler.init_noise_sigma

						# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
						# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
						# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
						# and should be between [0, 1]
						A__							:   Any					       =		"""eta""" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
						A__							:   Tuple					       =		{}
						if accepts_eta:
							A__							:   str					       =		eta

						for i, t in enumerate(self.progress_bar(A__      )      ):
							# expand the latents if we are doing classifier free guidance
							A__							:   Dict					       =		torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
							A__							:   Tuple					       =		self.scheduler.scale_model_input(A__   ,	A__      )

							# predict the noise residual
							A__							:   Union[str, Any]					       =		self.unet(A__   ,	A__   ,	encoder_hidden_states=A__      ).sample

							# perform guidance
							if do_classifier_free_guidance:
								A__       ,       A__							:   List[Any]					       =		noise_pred.chunk(2      )
								A__							:   Dict					       =		noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

							# compute the previous noisy sample x_t -> x_t-1
							A__							:   Tuple					       =		self.scheduler.step(A__   ,	A__   ,	A__   ,	**A__      ).prev_sample

							# call the callback, if provided
							if callback is not None and i % callback_steps == 0:
								callback(A__   ,	A__   ,	A__      )

						A__							:   str					       =		1 / 0.1_8_2_1_5 * latents
						A__							:   Optional[Any]					       =		self.vae.decode(A__      ).sample

						A__							:   Tuple					       =		(image / 2 + 0.5).clamp(0   ,	1      )

						# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
						A__							:   Any					       =		image.cpu().permute(0   ,	2   ,	3   ,	1      ).float().numpy()

						if output_type == "pil":
							A__							:   Optional[Any]					       =		self.numpy_to_pil(A__      )

						if not return_dict:
							return image

						return StableDiffusionPipelineOutput(images=A__   ,	nsfw_content_detected=A__      )



