
from dataclasses import dataclass
from typing import List, Optional, Union

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

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowercase__	:Optional[Any]										=					logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase__	:Union[str, Any]										=					"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n        ```\n"







@dataclass
class        lowercase	(      SCREAMING_SNAKE_CASE__	):
							lowercase_ : Union[PIL.Image.Image, np.ndarray]







class        lowercase	(      SCREAMING_SNAKE_CASE__	):




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

												self.register_modules(
												    prior=A__     ,image_encoder=A__     ,image_processor=A__     ,scheduler=A__     ,renderer=A__     ,)




							def 				A__   (       self     ,A__     ,A__     ,A__     ,A__     ,A__     ,A__):
												if latents is None:
																	lowercase					=		randn_tensor(A__     ,generator=A__     ,device=A__     ,dtype=A__)
												else:
																	if latents.shape != shape:
																						raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}')
																	lowercase					=		latents.to(A__)

												lowercase					=		latents * scheduler.init_noise_sigma
												return latents




							def 				A__   (       self     ,A__=0):
												if is_accelerate_available():
																	from accelerate import cpu_offload
												else:
																	raise ImportError('''Please install accelerate via `pip install accelerate`''')

												lowercase					=		torch.device(f'cuda:{gpu_id}')

												lowercase					=		[self.image_encoder, self.prior]
												for cpu_offloaded_model in models:
																	if cpu_offloaded_model is not None:
																						cpu_offload(A__     ,A__)




							@property
							def 				A__   (       self):
												if self.device != torch.device('''meta''') or not hasattr(self.image_encoder     ,'''_hf_hook'''):
																	return self.device
												for module in self.image_encoder.modules():
																	if (
																	    hasattr(A__     ,'''_hf_hook''')
																	    and hasattr(module._hf_hook     ,'''execution_device''')
																	    and module._hf_hook.execution_device is not None
																	):
																						return torch.device(module._hf_hook.execution_device)
												return self.device




							def 				A__   (       self     ,A__     ,A__     ,A__     ,A__     ,):
												if isinstance(A__     ,A__) and isinstance(image[0]     ,torch.Tensor):
																	lowercase					=		torch.cat(A__     ,axis=0) if image[0].ndim == 4 else torch.stack(A__     ,axis=0)

												if not isinstance(A__     ,torch.Tensor):
																	lowercase					=		self.image_processor(A__     ,return_tensors='''pt''').pixel_values[0].unsqueeze(0)

												lowercase					=		image.to(dtype=self.image_encoder.dtype     ,device=A__)

												lowercase					=		self.image_encoder(A__)['''last_hidden_state''']
												lowercase					=		image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

												lowercase					=		image_embeds.repeat_interleave(A__     ,dim=0)

												if do_classifier_free_guidance:
																	lowercase					=		torch.zeros_like(A__)

																	# 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
																	lowercase					=		torch.cat([negative_image_embeds, image_embeds])

												return image_embeds





							@torch.no_grad()
							@replace_example_docstring(A__)
							def __call__(       self     ,A__     ,A__ = 1     ,A__ = 2_5     ,A__ = None     ,A__ = None     ,A__ = 4.0     ,A__ = 6_4     ,A__ = "pil"     ,A__ = True     ,):

												if isinstance(A__     ,PIL.Image.Image):
																	lowercase					=		1
												elif isinstance(A__     ,torch.Tensor):
																	lowercase					=		image.shape[0]
												elif isinstance(A__     ,A__) and isinstance(image[0]     ,(torch.Tensor, PIL.Image.Image)):
																	lowercase					=		len(A__)
												else:
																	raise ValueError(
																	    f'`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(A__)}')

												lowercase					=		self._execution_device

												lowercase					=		batch_size * num_images_per_prompt

												lowercase					=		guidance_scale > 1.0
												lowercase					=		self._encode_image(A__     ,A__     ,A__     ,A__)

												# prior

												self.scheduler.set_timesteps(A__     ,device=A__)
												lowercase					=		self.scheduler.timesteps

												lowercase					=		self.prior.config.num_embeddings
												lowercase					=		self.prior.config.embedding_dim

												lowercase					=		self.prepare_latents(
												    (batch_size, num_embeddings * embedding_dim)     ,image_embeds.dtype     ,A__     ,A__     ,A__     ,self.scheduler     ,)

												# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
												lowercase					=		latents.reshape(latents.shape[0]     ,A__     ,A__)

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

																	lowercase					=		self.prior(
																	    A__     ,timestep=A__     ,proj_embedding=A__     ,).predicted_image_embedding

																	# remove the variance
																	lowercase			,		lowercase					=		noise_pred.split(
																	    scaled_model_input.shape[2]     ,dim=2)  # batch_size, num_embeddings, embedding_dim

																	if do_classifier_free_guidance is not None:
																						lowercase			,		lowercase					=		noise_pred.chunk(2)
																						lowercase					=		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																	lowercase					=		self.scheduler.step(
																	    A__     ,timestep=A__     ,sample=A__     ,).prev_sample

												if output_type == "latent":
																	return ShapEPipelineOutput(images=A__)

												lowercase					=		[]
												for i, latent in enumerate(A__):
																	print()
																	lowercase					=		self.renderer.decode(
																	    latent[None, :]     ,A__     ,size=A__     ,ray_batch_size=4_0_9_6     ,n_coarse_samples=6_4     ,n_fine_samples=1_2_8     ,)

																	images.append(A__)

												lowercase					=		torch.stack(A__)

												if output_type not in ["np", "pil"]:
																	raise ValueError(f'Only the output types `pil` and `np` are supported not output_type={output_type}')

												lowercase					=		images.cpu().numpy()

												if output_type == "pil":
																	lowercase					=		[self.numpy_to_pil(A__) for image in images]

												# Offload last model to CPU
												if hasattr(self     ,'''final_offload_hook''') and self.final_offload_hook is not None:
																	self.final_offload_hook.offload()

												if not return_dict:
																	return (images,)

												return ShapEPipelineOutput(images=A__)






import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest







class        lowercase	(      SCREAMING_SNAKE_CASE__	):
							lowercase_ : List[str]       =(UniPCMultistepScheduler,)
							lowercase_ : Tuple       =(('''num_inference_steps''', 25),)




							def 				A__   (       self     ,**A__):
												lowercase					=		{
												    '''num_train_timesteps''': 1_0_0_0,
												    '''beta_start''': 0.0001,
												    '''beta_end''': 0.02,
												    '''beta_schedule''': '''linear''',
												    '''solver_order''': 2,
												    '''solver_type''': '''bh2''',
												}

												config.update(**A__)
												return config




							def 				A__   (       self     ,A__=0     ,**A__):
												lowercase					=		dict(self.forward_default_kwargs)
												lowercase					=		kwargs.pop('''num_inference_steps'''     ,A__)
												lowercase					=		self.dummy_sample
												lowercase					=		0.1 * sample
												lowercase					=		[residual + 0.2, residual + 0.15, residual + 0.10]

												for scheduler_class in self.scheduler_classes:
																	lowercase					=		self.get_scheduler_config(**A__)
																	lowercase					=		scheduler_class(**A__)
																	scheduler.set_timesteps(A__)
																	# copy over dummy past residuals
																	lowercase					=		dummy_past_residuals[: scheduler.config.solver_order]

																	with tempfile.TemporaryDirectory() as tmpdirname:
																						scheduler.save_config(A__)
																						lowercase					=		scheduler_class.from_pretrained(A__)
																						new_scheduler.set_timesteps(A__)
																						# copy over dummy past residuals
																						lowercase					=		dummy_past_residuals[: new_scheduler.config.solver_order]

																	lowercase			,		lowercase					=		sample, sample
																	for t in range(A__     ,time_step + scheduler.config.solver_order + 1):
																						lowercase					=		scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample
																						lowercase					=		new_scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample

																						assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical"




							def 				A__   (       self     ,A__=0     ,**A__):
												lowercase					=		dict(self.forward_default_kwargs)
												lowercase					=		kwargs.pop('''num_inference_steps'''     ,A__)
												lowercase					=		self.dummy_sample
												lowercase					=		0.1 * sample
												lowercase					=		[residual + 0.2, residual + 0.15, residual + 0.10]

												for scheduler_class in self.scheduler_classes:
																	lowercase					=		self.get_scheduler_config()
																	lowercase					=		scheduler_class(**A__)
																	scheduler.set_timesteps(A__)

																	# copy over dummy past residuals (must be after setting timesteps)
																	lowercase					=		dummy_past_residuals[: scheduler.config.solver_order]

																	with tempfile.TemporaryDirectory() as tmpdirname:
																						scheduler.save_config(A__)
																						lowercase					=		scheduler_class.from_pretrained(A__)
																						# copy over dummy past residuals
																						new_scheduler.set_timesteps(A__)

																						# copy over dummy past residual (must be after setting timesteps)
																						lowercase					=		dummy_past_residuals[: new_scheduler.config.solver_order]

																	lowercase					=		scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample
																	lowercase					=		new_scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample

																	assert torch.sum(torch.abs(output - new_output)) < 1E-5, "Scheduler outputs are not identical"




							def 				A__   (       self     ,A__=None     ,**A__):
												if scheduler is None:
																	lowercase					=		self.scheduler_classes[0]
																	lowercase					=		self.get_scheduler_config(**A__)
																	lowercase					=		scheduler_class(**A__)

												lowercase					=		self.scheduler_classes[0]
												lowercase					=		self.get_scheduler_config(**A__)
												lowercase					=		scheduler_class(**A__)

												lowercase					=		1_0
												lowercase					=		self.dummy_model()
												lowercase					=		self.dummy_sample_deter
												scheduler.set_timesteps(A__)

												for i, t in enumerate(scheduler.timesteps):
																	lowercase					=		model(A__     ,A__)
																	lowercase					=		scheduler.step(A__     ,A__     ,A__).prev_sample

												return sample




							def 				A__   (       self):
												lowercase					=		dict(self.forward_default_kwargs)

												lowercase					=		kwargs.pop('''num_inference_steps'''     ,A__)

												for scheduler_class in self.scheduler_classes:
																	lowercase					=		self.get_scheduler_config()
																	lowercase					=		scheduler_class(**A__)

																	lowercase					=		self.dummy_sample
																	lowercase					=		0.1 * sample

																	if num_inference_steps is not None and hasattr(A__     ,'''set_timesteps'''):
																						scheduler.set_timesteps(A__)
																	elif num_inference_steps is not None and not hasattr(A__     ,'''set_timesteps'''):
																						lowercase					=		num_inference_steps

																	# copy over dummy past residuals (must be done after set_timesteps)
																	lowercase					=		[residual + 0.2, residual + 0.15, residual + 0.10]
																	lowercase					=		dummy_past_residuals[: scheduler.config.solver_order]

																	lowercase					=		scheduler.timesteps[5]
																	lowercase					=		scheduler.timesteps[6]

																	lowercase					=		scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample
																	lowercase					=		scheduler.step(A__     ,A__     ,A__     ,**A__).prev_sample

																	self.assertEqual(output_a.shape     ,sample.shape)
																	self.assertEqual(output_a.shape     ,output_a.shape)




							def 				A__   (       self):
												# make sure that iterating over schedulers with same config names gives same results
												# for defaults
												lowercase					=		UniPCMultistepScheduler(**self.get_scheduler_config())
												lowercase					=		self.full_loop(scheduler=A__)
												lowercase					=		torch.mean(torch.abs(A__))

												assert abs(result_mean.item() - 0.2464) < 1E-3

												lowercase					=		DPMSolverSinglestepScheduler.from_config(scheduler.config)
												lowercase					=		DEISMultistepScheduler.from_config(scheduler.config)
												lowercase					=		DPMSolverMultistepScheduler.from_config(scheduler.config)
												lowercase					=		UniPCMultistepScheduler.from_config(scheduler.config)

												lowercase					=		self.full_loop(scheduler=A__)
												lowercase					=		torch.mean(torch.abs(A__))

												assert abs(result_mean.item() - 0.2464) < 1E-3




							def 				A__   (       self):
												for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
																	self.check_over_configs(num_train_timesteps=A__)




							def 				A__   (       self):
												self.check_over_configs(thresholding=A__)
												for order in [1, 2, 3]:
																	for solver_type in ["bh1", "bh2"]:
																						for threshold in [0.5, 1.0, 2.0]:
																											for prediction_type in ["epsilon", "sample"]:
																																self.check_over_configs(
																																    thresholding=A__     ,prediction_type=A__     ,sample_max_value=A__     ,solver_order=A__     ,solver_type=A__     ,)




							def 				A__   (       self):
												for prediction_type in ["epsilon", "v_prediction"]:
																	self.check_over_configs(prediction_type=A__)




							def 				A__   (       self):
												for solver_type in ["bh1", "bh2"]:
																	for order in [1, 2, 3]:
																						for prediction_type in ["epsilon", "sample"]:
																											self.check_over_configs(
																											    solver_order=A__     ,solver_type=A__     ,prediction_type=A__     ,)
																											lowercase					=		self.full_loop(
																											    solver_order=A__     ,solver_type=A__     ,prediction_type=A__     ,)
																											assert not torch.isnan(A__).any(), "Samples have nan numbers"




							def 				A__   (       self):
												self.check_over_configs(lower_order_final=A__)
												self.check_over_configs(lower_order_final=A__)




							def 				A__   (       self):
												for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
																	self.check_over_forward(num_inference_steps=A__     ,time_step=0)




							def 				A__   (       self):
												lowercase					=		self.full_loop()
												lowercase					=		torch.mean(torch.abs(A__))

												assert abs(result_mean.item() - 0.2464) < 1E-3




							def 				A__   (       self):
												lowercase					=		self.full_loop(prediction_type='''v_prediction''')
												lowercase					=		torch.mean(torch.abs(A__))

												assert abs(result_mean.item() - 0.1014) < 1E-3




							def 				A__   (       self):
												lowercase					=		self.scheduler_classes[0]
												lowercase					=		self.get_scheduler_config(thresholding=A__     ,dynamic_thresholding_ratio=0)
												lowercase					=		scheduler_class(**A__)

												lowercase					=		1_0
												lowercase					=		self.dummy_model()
												lowercase					=		self.dummy_sample_deter.half()
												scheduler.set_timesteps(A__)

												for i, t in enumerate(scheduler.timesteps):
																	lowercase					=		model(A__     ,A__)
																	lowercase					=		scheduler.step(A__     ,A__     ,A__).prev_sample

												assert sample.dtype == torch.floataa





							def 				A__   (       self     ,**A__):
												for scheduler_class in self.scheduler_classes:
																	lowercase					=		self.get_scheduler_config(**A__)
																	lowercase					=		scheduler_class(**A__)

																	scheduler.set_timesteps(scheduler.config.num_train_timesteps)
																	assert len(scheduler.timesteps.unique()) == scheduler.num_inference_steps




