






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


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

A__      :     int       =					'\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  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				lowercase__											=			42



class  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				def __init__(	self		:       Optional[int],    lowerCamelCase		:       PriorTransformer,    lowerCamelCase		:       CLIPVisionModel,    lowerCamelCase		:       CLIPImageProcessor,    lowerCamelCase		:       HeunDiscreteScheduler,    lowerCamelCase		:       ShapERenderer,    ):

								'''simple docstring'''
								super().__init__()

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




				def 							lowercase__  (	self		:       Tuple,    lowerCamelCase		:       Dict,    lowerCamelCase		:       Dict,    lowerCamelCase		:       List[str],    lowerCamelCase		:       Union[str, Any],    lowerCamelCase		:       List[Any],    lowerCamelCase		:       Any    ):

								'''simple docstring'''
								if latents is None:
												lowercase__  					=     randn_tensor(lowerCamelCase,    generator=lowerCamelCase,    device=lowerCamelCase,    dtype=lowerCamelCase    )
								else:
												if latents.shape != shape:
																raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""    )
												lowercase__  					=     latents.to(lowerCamelCase    )

								lowercase__  					=     latents * scheduler.init_noise_sigma
								return latents




				def 							lowercase__  (	self		:       Dict,    lowerCamelCase		:       Dict=0    ):

								'''simple docstring'''
								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(lowerCamelCase,    lowerCamelCase    )




				@property
				def 							lowercase__  (	self		:       Optional[int]    ):

								'''simple docstring'''
								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(lowerCamelCase,    '''_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 							lowercase__  (	self		:       Any,    lowerCamelCase		:       Optional[int],    lowerCamelCase		:       List[Any],    lowerCamelCase		:       Tuple,    lowerCamelCase		:       List[str],    ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,    lowerCamelCase    ) and isinstance(image[0],    torch.Tensor    ):
												lowercase__  					=     torch.cat(lowerCamelCase,    axis=0    ) if image[0].ndim == 4 else torch.stack(lowerCamelCase,    axis=0    )

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

								lowercase__  					=     image.to(dtype=self.image_encoder.dtype,    device=lowerCamelCase    )

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

								lowercase__  					=     image_embeds.repeat_interleave(lowerCamelCase,    dim=0    )

								if do_classifier_free_guidance:
												lowercase__  					=     torch.zeros_like(lowerCamelCase    )

												# 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(lowerCamelCase    )
				def __call__(	self		:       Tuple,    lowerCamelCase		:       Union[PIL.Image.Image, List[PIL.Image.Image]],    lowerCamelCase		:       int = 1,    lowerCamelCase		:       int = 25,    lowerCamelCase		:       Optional[Union[torch.Generator, List[torch.Generator]]] = None,    lowerCamelCase		:       Optional[torch.FloatTensor] = None,    lowerCamelCase		:       float = 4.0,    lowerCamelCase		:       int = 64,    lowerCamelCase		:       Optional[str] = "pil",    lowerCamelCase		:       bool = True,    ):

								'''simple docstring'''

								if isinstance(lowerCamelCase,    PIL.Image.Image    ):
												lowercase__  					=     1
								elif isinstance(lowerCamelCase,    torch.Tensor    ):
												lowercase__  					=     image.shape[0]
								elif isinstance(lowerCamelCase,    lowerCamelCase    ) and isinstance(image[0],    (torch.Tensor, PIL.Image.Image)    ):
												lowercase__  					=     len(lowerCamelCase    )
								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(lowerCamelCase    )}"""    )

								lowercase__  					=     self._execution_device

								lowercase__  					=     batch_size * num_images_per_prompt

								lowercase__  					=     guidance_scale > 1.0
								lowercase__  					=     self._encode_image(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    lowerCamelCase    )

								# prior

								self.scheduler.set_timesteps(lowerCamelCase,    device=lowerCamelCase    )
								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,    lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    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],    lowerCamelCase,    lowerCamelCase    )

								for i, t in enumerate(self.progress_bar(lowerCamelCase    )    ):
												# 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(lowerCamelCase,    lowerCamelCase    )

												lowercase__  					=     self.prior(
												    lowerCamelCase,    timestep=lowerCamelCase,    proj_embedding=lowerCamelCase,    ).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(
												    lowerCamelCase,    timestep=lowerCamelCase,    sample=lowerCamelCase,    ).prev_sample

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

								lowercase__  					=     []
								for i, latent in enumerate(lowerCamelCase    ):
												print()
												lowercase__  					=     self.renderer.decode(
												    latent[None, :],    lowerCamelCase,    size=lowerCamelCase,    ray_batch_size=4_096,    n_coarse_samples=64,    n_fine_samples=128,    )

												images.append(lowerCamelCase    )

								lowercase__  					=     torch.stack(lowerCamelCase    )

								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(lowerCamelCase    ) 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=lowerCamelCase    )












import tempfile

import torch

from diffusers import IPNDMScheduler

from .test_schedulers import SchedulerCommonTest
class  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				lowercase__											=			(IPNDMScheduler,)
				lowercase__											=			(("""num_inference_steps""", 50),)




				def 							lowercase__  (	self		:       Union[str, Any],    **lowerCamelCase		:       Tuple    ):

								'''simple docstring'''
								lowercase__  					=     {'''num_train_timesteps''': 1_000}
								config.update(**lowerCamelCase    )
								return config




				def 							lowercase__  (	self		:       Any,    lowerCamelCase		:       Any=0,    **lowerCamelCase		:       List[str]    ):

								'''simple docstring'''
								lowercase__  					=     dict(self.forward_default_kwargs    )
								lowercase__  					=     kwargs.pop('''num_inference_steps''',    lowerCamelCase    )
								lowercase__  					=     self.dummy_sample
								lowercase__  					=     0.1 * sample
								lowercase__  					=     [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

								for scheduler_class in self.scheduler_classes:
												lowercase__  					=     self.get_scheduler_config(**lowerCamelCase    )
												lowercase__  					=     scheduler_class(**lowerCamelCase    )
												scheduler.set_timesteps(lowerCamelCase    )
												# copy over dummy past residuals
												lowercase__  					=     dummy_past_residuals[:]

												if time_step is None:
																lowercase__  					=     scheduler.timesteps[len(scheduler.timesteps    ) // 2]

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

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     new_scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     new_scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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




				def 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								pass




				def 							lowercase__  (	self		:       Dict,    lowerCamelCase		:       Optional[int]=0,    **lowerCamelCase		:       Dict    ):

								'''simple docstring'''
								lowercase__  					=     dict(self.forward_default_kwargs    )
								lowercase__  					=     kwargs.pop('''num_inference_steps''',    lowerCamelCase    )
								lowercase__  					=     self.dummy_sample
								lowercase__  					=     0.1 * sample
								lowercase__  					=     [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

								for scheduler_class in self.scheduler_classes:
												lowercase__  					=     self.get_scheduler_config()
												lowercase__  					=     scheduler_class(**lowerCamelCase    )
												scheduler.set_timesteps(lowerCamelCase    )

												# copy over dummy past residuals (must be after setting timesteps)
												lowercase__  					=     dummy_past_residuals[:]

												if time_step is None:
																lowercase__  					=     scheduler.timesteps[len(scheduler.timesteps    ) // 2]

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

																# copy over dummy past residual (must be after setting timesteps)
																lowercase__  					=     dummy_past_residuals[:]

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     new_scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     new_scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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




				def 							lowercase__  (	self		:       int,    **lowerCamelCase		:       List[str]    ):

								'''simple docstring'''
								lowercase__  					=     self.scheduler_classes[0]
								lowercase__  					=     self.get_scheduler_config(**lowerCamelCase    )
								lowercase__  					=     scheduler_class(**lowerCamelCase    )

								lowercase__  					=     10
								lowercase__  					=     self.dummy_model()
								lowercase__  					=     self.dummy_sample_deter
								scheduler.set_timesteps(lowerCamelCase    )

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

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

								return sample




				def 							lowercase__  (	self		:       List[Any]    ):

								'''simple docstring'''
								lowercase__  					=     dict(self.forward_default_kwargs    )

								lowercase__  					=     kwargs.pop('''num_inference_steps''',    lowerCamelCase    )

								for scheduler_class in self.scheduler_classes:
												lowercase__  					=     self.get_scheduler_config()
												lowercase__  					=     scheduler_class(**lowerCamelCase    )

												lowercase__  					=     self.dummy_sample
												lowercase__  					=     0.1 * sample

												if num_inference_steps is not None and hasattr(lowerCamelCase,    '''set_timesteps'''    ):
																scheduler.set_timesteps(lowerCamelCase    )
												elif num_inference_steps is not None and not hasattr(lowerCamelCase,    '''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.1, residual + 0.05]
												lowercase__  					=     dummy_past_residuals[:]

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

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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

												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample
												lowercase__  					=     scheduler.step(lowerCamelCase,    lowerCamelCase,    lowerCamelCase,    **lowerCamelCase    ).prev_sample

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




				def 							lowercase__  (	self		:       Dict    ):

								'''simple docstring'''
								for timesteps in [100, 1_000]:
												self.check_over_configs(num_train_timesteps=lowerCamelCase,    time_step=lowerCamelCase    )




				def 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								for t, num_inference_steps in zip([1, 5, 10],    [10, 50, 100]    ):
												self.check_over_forward(num_inference_steps=lowerCamelCase,    time_step=lowerCamelCase    )




				def 							lowercase__  (	self		:       List[str]    ):

								'''simple docstring'''
								lowercase__  					=     self.full_loop()
								lowercase__  					=     torch.mean(torch.abs(lowerCamelCase    )    )

								assert abs(result_mean.item() - 2_540_529    ) < 10




