




'''simple docstring'''







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

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

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


lowercase			:      Tuple			=					logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase			:      Union[str, Any]			=					"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

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

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

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

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

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







@dataclass
class 				_a   (a__  ):





     '''simple docstring'''



     lowerCAmelCase_     :    Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class 				_a   (a__  ):





     '''simple docstring'''



     def __init__(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,)			->							Tuple:
          super().__init__()

          self.register_modules(
              prior=__a       ,text_encoder=__a       ,tokenizer=__a       ,scheduler=__a       ,renderer=__a       ,)







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							List[Any]:
          if latents is None:
               snake_case :			List[str]					   = 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}'''       )
               snake_case :			Union[str, Any]					   = latents.to(__a       )

          snake_case :			Any					   = latents * scheduler.init_noise_sigma
          return latents







     def  snake_case_			(							self       ,__a=0       )			->							List[str]:
          if is_accelerate_available():
               from accelerate import cpu_offload
          else:
               raise ImportError("""Please install accelerate via `pip install accelerate`"""       )

          snake_case :			List[Any]					   = torch.device(F'''cuda:{gpu_id}'''       )

          snake_case :			List[Any]					   = [self.text_encoder, self.prior]
          for cpu_offloaded_model in models:
               if cpu_offloaded_model is not None:
                    cpu_offload(__a       ,__a       )







     def  snake_case_			(							self       ,__a=0       )			->							int:
          if is_accelerate_available() and is_accelerate_version(""">="""       ,"""0.17.0.dev0"""       ):
               from accelerate import cpu_offload_with_hook
          else:
               raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""       )

          snake_case :			Dict					   = torch.device(F'''cuda:{gpu_id}'''       )

          if self.device.type != "cpu":
               self.to("""cpu"""       ,silence_dtype_warnings=__a       )
               torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

          snake_case :			List[Any]					   = None
          for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
               snake_case   ,		snake_case :			int					   = cpu_offload_with_hook(__a       ,__a       ,prev_module_hook=__a       )

          if self.safety_checker is not None:
               snake_case   ,		snake_case :			int					   = cpu_offload_with_hook(self.safety_checker       ,__a       ,prev_module_hook=__a       )

          # We'll offload the last model manually.
          snake_case :			Dict					   = hook







     @property
     def  snake_case_			(							self       )			->							Tuple:
          if self.device != torch.device("""meta"""       ) or not hasattr(self.text_encoder       ,"""_hf_hook"""       ):
               return self.device
          for module in self.text_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  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,)			->							str:
          len(__a       ) if isinstance(__a       ,__a       ) else 1

          # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
          snake_case :			Tuple					   = 0
          # get prompt text embeddings
          snake_case :			Union[str, Any]					   = self.tokenizer(
              __a       ,padding="""max_length"""       ,max_length=self.tokenizer.model_max_length       ,truncation=__a       ,return_tensors="""pt"""       ,)
          snake_case :			Union[str, Any]					   = text_inputs.input_ids
          snake_case :			Union[str, Any]					   = self.tokenizer(__a       ,padding="""longest"""       ,return_tensors="""pt"""       ).input_ids

          if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__a       ,__a       ):
               snake_case :			Any					   = 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}'''       )

          snake_case :			List[str]					   = self.text_encoder(text_input_ids.to(__a       )       )
          snake_case :			int					   = text_encoder_output.text_embeds

          snake_case :			Any					   = prompt_embeds.repeat_interleave(__a       ,dim=0       )
          # in Shap-E it normalize the prompt_embeds and then later rescale it
          snake_case :			Any					   = prompt_embeds / torch.linalg.norm(__a       ,dim=-1       ,keepdim=__a       )

          if do_classifier_free_guidance:
               snake_case :			Optional[int]					   = 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
               snake_case :			List[str]					   = torch.cat([negative_prompt_embeds, prompt_embeds]       )

          # Rescale the features to have unit variance
          snake_case :			List[Any]					   = math.sqrt(prompt_embeds.shape[1]       ) * prompt_embeds

          return prompt_embeds







     @torch.no_grad()
     @replace_example_docstring(__a       )
     def __call__(							self       ,__a       ,__a = 1       ,__a = 25       ,__a = None       ,__a = None       ,__a = 4.0       ,__a = 64       ,__a = "pil"       ,__a = True       ,)			->							List[str]:

          if isinstance(__a       ,__a       ):
               snake_case :			List[str]					   = 1
          elif isinstance(__a       ,__a       ):
               snake_case :			str					   = len(__a       )
          else:
               raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(__a       )}'''       )

          snake_case :			List[Any]					   = self._execution_device

          snake_case :			str					   = batch_size * num_images_per_prompt

          snake_case :			str					   = guidance_scale > 1.0
          snake_case :			int					   = self._encode_prompt(__a       ,__a       ,__a       ,__a       )

          # prior

          self.scheduler.set_timesteps(__a       ,device=__a       )
          snake_case :			Optional[int]					   = self.scheduler.timesteps

          snake_case :			Optional[int]					   = self.prior.config.num_embeddings
          snake_case :			int					   = self.prior.config.embedding_dim

          snake_case :			Optional[Any]					   = self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim)       ,prompt_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
          snake_case :			Any					   = 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
               snake_case :			int					   = torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
               snake_case :			int					   = self.scheduler.scale_model_input(__a       ,__a       )

               snake_case :			Optional[Any]					   = self.prior(
                   __a       ,timestep=__a       ,proj_embedding=__a       ,).predicted_image_embedding

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

               if do_classifier_free_guidance is not None:
                    snake_case   ,		snake_case :			Optional[Any]					   = noise_pred.chunk(2       )
                    snake_case :			Tuple					   = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

               snake_case :			List[str]					   = self.scheduler.step(
                   __a       ,timestep=__a       ,sample=__a       ,).prev_sample

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

          snake_case :			Optional[int]					   = []
          for i, latent in enumerate(__a       ):
               snake_case :			List[Any]					   = self.renderer.decode(
                   latent[None, :]       ,__a       ,size=__a       ,ray_batch_size=4_096       ,n_coarse_samples=64       ,n_fine_samples=128       ,)
               images.append(__a       )

          snake_case :			Dict					   = 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}'''       )

          snake_case :			int					   = images.cpu().numpy()

          if output_type == "pil":
               snake_case :			Tuple					   = [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       )









'''simple docstring'''







def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 491.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 32) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 32) * 5 / 9) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 273.15) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 491.67) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 5 / 9)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25 + 273.15)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32 + 459.67)    ,      __lowercase							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()



