




'''simple docstring'''




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_      :		Optional[Any]							      =       """
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""


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





class   __UpperCamelCase       ( lowerCamelCase__				):






       def __init__(							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		):



              """simple docstring"""







              super().__init__()

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






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              if latents is None:
                     lowerCamelCase_							=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}'''  )
                     lowerCamelCase_							=latents.to(lowerCAmelCase  )

              lowerCamelCase_							=latents * scheduler.init_noise_sigma
              return latents






       def      lowercase__     (							self,		lowerCAmelCase=0  ):



              """simple docstring"""







              if is_accelerate_available():
                     from accelerate import cpu_offload
              else:
                     raise ImportError('''Please install accelerate via `pip install accelerate`'''  )

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

              lowerCamelCase_							=[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  ):



              """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,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		):



              """simple docstring"""







              if isinstance(lowerCAmelCase,		lowerCAmelCase  ) and isinstance(image[0],		torch.Tensor  ):
                     lowerCamelCase_							=torch.cat(lowerCAmelCase,		axis=0  ) if image[0].ndim == 4 else torch.stack(lowerCAmelCase,		axis=0  )

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

              lowerCamelCase_							=image.to(dtype=self.image_encoder.dtype,		device=lowerCAmelCase  )

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

              lowerCamelCase_							=image_embeds.repeat_interleave(lowerCAmelCase,		dim=0  )

              if do_classifier_free_guidance:
                     lowerCamelCase_							=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
                     lowerCamelCase_							=torch.cat([negative_image_embeds, image_embeds]  )

              return image_embeds






       @torch.no_grad()
       @replace_example_docstring(lowerCAmelCase  )
       def __call__(							self,		lowerCAmelCase,		lowerCAmelCase = 1,		lowerCAmelCase = 25,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = 4.0,		lowerCAmelCase = 64,		lowerCAmelCase = "pil",		lowerCAmelCase = True,		):



              """simple docstring"""







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

              lowerCamelCase_							=self._execution_device

              lowerCamelCase_							=batch_size * num_images_per_prompt

              lowerCamelCase_							=guidance_scale > 1.0
              lowerCamelCase_							=self._encode_image(lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  )

              # prior

              self.scheduler.set_timesteps(lowerCAmelCase,		device=lowerCAmelCase  )
              lowerCamelCase_							=self.scheduler.timesteps

              lowerCamelCase_							=self.prior.config.num_embeddings
              lowerCamelCase_							=self.prior.config.embedding_dim

              lowerCamelCase_							=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
              lowerCamelCase_							=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
                     lowerCamelCase_							=torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents
                     lowerCamelCase_							=self.scheduler.scale_model_input(lowerCAmelCase,		lowerCAmelCase  )

                     lowerCamelCase_							=self.prior(
                         lowerCAmelCase,		timestep=lowerCAmelCase,		proj_embedding=lowerCAmelCase,		).predicted_image_embedding

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

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

                     lowerCamelCase_							=self.scheduler.step(
                         lowerCAmelCase,		timestep=lowerCAmelCase,		sample=lowerCAmelCase,		).prev_sample

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

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

                     images.append(lowerCAmelCase  )

              lowerCamelCase_							=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}'''  )

              lowerCamelCase_							=images.cpu().numpy()

              if output_type == "pil":
                     lowerCamelCase_							=[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 torch

from diffusers import DDPMScheduler

from .test_schedulers import SchedulerCommonTest



class 	_lowercase							(   lowerCAmelCase	):





	"""simple docstring"""
	__A							=							(DDPMScheduler,)




	def      UpperCamelCase_       (self		,       **lowerCamelCase_		):
						"""simple docstring"""

						a					     =   {
						    "num_train_timesteps": 1000,
						    "beta_start": 0.0001,
						    "beta_end": 0.02,
						    "beta_schedule": "linear",
						    "variance_type": "fixed_small",
						    "clip_sample": True,
						}

						config.update(**lowerCamelCase_		)
						return config




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for timesteps in [1, 5, 100, 1000]:
											self.check_over_configs(num_train_timesteps=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1]		,       [0.002, 0.02, 0.2, 2]		):
											self.check_over_configs(beta_start=lowerCamelCase_		,       beta_end=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for schedule in ["linear", "squaredcos_cap_v2"]:
											self.check_over_configs(beta_schedule=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for variance in ["fixed_small", "fixed_large", "other"]:
											self.check_over_configs(variance_type=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for clip_sample in [True, False]:
											self.check_over_configs(clip_sample=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						self.check_over_configs(thresholding=lowerCamelCase_		)
						for threshold in [0.5, 1.0, 2.0]:
											for prediction_type in ["epsilon", "sample", "v_prediction"]:
																self.check_over_configs(
																    thresholding=lowerCamelCase_		,       prediction_type=lowerCamelCase_		,       sample_max_value=lowerCamelCase_		,       )




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

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




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for t in [0, 500, 999]:
											self.check_over_forward(time_step=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						assert torch.sum(torch.abs(scheduler._get_variance(0		) - 0.0		)		) < 1E-5
						assert torch.sum(torch.abs(scheduler._get_variance(487		) - 0.0_0979		)		) < 1E-5
						assert torch.sum(torch.abs(scheduler._get_variance(999		) - 0.02		)		) < 1E-5




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   len(lowerCamelCase_		)

						a					     =   self.dummy_model()
						a					     =   self.dummy_sample_deter
						a					     =   torch.manual_seed(0		)

						for t in reversed(range(lowerCamelCase_		)		):
											# 1. predict noise residual
											a					     =   model(lowerCamelCase_		,       lowerCamelCase_		)

											# 2. predict previous mean of sample x_t-1
											a					     =   scheduler.step(lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       generator=lowerCamelCase_		).prev_sample

											# if t > 0:
											#     noise = self.dummy_sample_deter
											#     variance = scheduler.get_variance(t) ** (0.5) * noise
											#
											# sample = pred_prev_sample + variance
											a					     =   pred_prev_sample

						a					     =   torch.sum(torch.abs(lowerCamelCase_		)		)
						a					     =   torch.mean(torch.abs(lowerCamelCase_		)		)

						assert abs(result_sum.item() - 258.9606		) < 1E-2
						assert abs(result_mean.item() - 0.3372		) < 1E-3




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config(prediction_type="v_prediction"		)
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   len(lowerCamelCase_		)

						a					     =   self.dummy_model()
						a					     =   self.dummy_sample_deter
						a					     =   torch.manual_seed(0		)

						for t in reversed(range(lowerCamelCase_		)		):
											# 1. predict noise residual
											a					     =   model(lowerCamelCase_		,       lowerCamelCase_		)

											# 2. predict previous mean of sample x_t-1
											a					     =   scheduler.step(lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       generator=lowerCamelCase_		).prev_sample

											# if t > 0:
											#     noise = self.dummy_sample_deter
											#     variance = scheduler.get_variance(t) ** (0.5) * noise
											#
											# sample = pred_prev_sample + variance
											a					     =   pred_prev_sample

						a					     =   torch.sum(torch.abs(lowerCamelCase_		)		)
						a					     =   torch.mean(torch.abs(lowerCamelCase_		)		)

						assert abs(result_sum.item() - 202.0296		) < 1E-2
						assert abs(result_mean.item() - 0.2631		) < 1E-3




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   [100, 87, 50, 1, 0]

						scheduler.set_timesteps(timesteps=lowerCamelCase_		)

						a					     =   scheduler.timesteps

						for i, timestep in enumerate(lowerCamelCase_		):
											if i == len(lowerCamelCase_		) - 1:
																a					     =   -1
											else:
																a					     =   timesteps[i + 1]

											a					     =   scheduler.previous_timestep(lowerCamelCase_		)
											a					     =   prev_t.item()

											self.assertEqual(lowerCamelCase_		,       lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   [100, 87, 50, 51, 0]

						with self.assertRaises(lowerCamelCase_		,       msg="`custom_timesteps` must be in descending order."		):
											scheduler.set_timesteps(timesteps=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   [100, 87, 50, 1, 0]
						a					     =   len(lowerCamelCase_		)

						with self.assertRaises(lowerCamelCase_		,       msg="Can only pass one of `num_inference_steps` or `custom_timesteps`."		):
											scheduler.set_timesteps(num_inference_steps=lowerCamelCase_		,       timesteps=lowerCamelCase_		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.scheduler_classes[0]
						a					     =   self.get_scheduler_config()
						a					     =   scheduler_class(**lowerCamelCase_		)

						a					     =   [scheduler.config.num_train_timesteps]

						with self.assertRaises(
						    lowerCamelCase_		,       msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}"		,       ):
											scheduler.set_timesteps(timesteps=lowerCamelCase_		)
