



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


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

__snake_case	:				Optional[Any]  					=			'\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\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], "shark_3d.gif")\n        ```\n'

@dataclass
class       UpperCamelCase  (					_UpperCAmelCase				):





     """simple docstring"""






     _lowerCamelCase					: int				   =42


class       UpperCamelCase  (					_UpperCAmelCase				):





     """simple docstring"""






     def __init__(					self :							Optional[int]	,      _lowerCamelCase :							Any	,      _lowerCamelCase :							str	,      _lowerCamelCase :							Any	,      _lowerCamelCase :							List[Any]	,      _lowerCamelCase :							Any	,      ):
          super().__init__()

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





     def 						A__  (					self :							Dict	,      _lowerCamelCase :							Any	,      _lowerCamelCase :							Optional[int]	,      _lowerCamelCase :							int	,      _lowerCamelCase :							Tuple	,      _lowerCamelCase :							Optional[Any]	,      _lowerCamelCase :							Any ):






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

          A__				=   latents * scheduler.init_noise_sigma
          return latents





     def 						A__  (					self :							Any	,      _lowerCamelCase :							Optional[int]=0 ):






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

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

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





     def 						A__  (					self :							Union[str, Any]	,      _lowerCamelCase :							Tuple=0 ):






          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.''' )

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

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

          A__				=   None
          for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
               A__	,     A__				=   cpu_offload_with_hook(_lowerCamelCase	,      _lowerCamelCase	,      prev_module_hook=_lowerCamelCase )

          if self.safety_checker is not None:
               A__	,     A__				=   cpu_offload_with_hook(self.safety_checker	,      _lowerCamelCase	,      prev_module_hook=_lowerCamelCase )

          # We'll offload the last model manually.
          A__				=   hook





     @property
     def 						A__  (					self :							List[Any] ):






          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(_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 						A__  (					self :							List[str]	,      _lowerCamelCase :							str	,      _lowerCamelCase :							Optional[Any]	,      _lowerCamelCase :							Dict	,      _lowerCamelCase :							int	,      ):
          len(_lowerCamelCase ) if isinstance(_lowerCamelCase	,      _lowerCamelCase ) else 1

          # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
          A__				=   0
          # get prompt text embeddings
          A__				=   self.tokenizer(
              _lowerCamelCase	,      padding='''max_length'''	,      max_length=self.tokenizer.model_max_length	,      truncation=_lowerCamelCase	,      return_tensors='''pt'''	,      )
          A__				=   text_inputs.input_ids
          A__				=   self.tokenizer(_lowerCamelCase	,      padding='''longest'''	,      return_tensors='''pt''' ).input_ids

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

          A__				=   self.text_encoder(text_input_ids.to(_lowerCamelCase ) )
          A__				=   text_encoder_output.text_embeds

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

          if do_classifier_free_guidance:
               A__				=   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
               A__				=   torch.cat([negative_prompt_embeds, prompt_embeds] )

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

          return prompt_embeds





     @torch.no_grad()
     @replace_example_docstring(_lowerCamelCase )
     def __call__(					self :							int	,      _lowerCamelCase :							Tuple	,      _lowerCamelCase :							int = 1	,      _lowerCamelCase :							Dict = 2_5	,      _lowerCamelCase :							int = None	,      _lowerCamelCase :							Union[str, Any] = None	,      _lowerCamelCase :							Any = 4.0	,      _lowerCamelCase :							Optional[Any] = 6_4	,      _lowerCamelCase :							Dict = "pil"	,      _lowerCamelCase :							Union[str, Any] = True	,      ):






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

          A__				=   self._execution_device

          A__				=   batch_size * num_images_per_prompt

          A__				=   guidance_scale > 1.0
          A__				=   self._encode_prompt(_lowerCamelCase	,      _lowerCamelCase	,      _lowerCamelCase	,      _lowerCamelCase )

          # prior

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

          A__				=   self.prior.config.num_embeddings
          A__				=   self.prior.config.embedding_dim

          A__				=   self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim)	,      prompt_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
          A__				=   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
               A__				=   torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
               A__				=   self.scheduler.scale_model_input(_lowerCamelCase	,      _lowerCamelCase )

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

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

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

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

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

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

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

          A__				=   images.cpu().numpy()

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








"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


__snake_case	:				List[Any]  					=			{
    'configuration_unispeech_sat': ['UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechSatConfig'],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __snake_case	:				str  					=			[
     'UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST',
     'UniSpeechSatForAudioFrameClassification',
     'UniSpeechSatForCTC',
     'UniSpeechSatForPreTraining',
     'UniSpeechSatForSequenceClassification',
     'UniSpeechSatForXVector',
     'UniSpeechSatModel',
     'UniSpeechSatPreTrainedModel',
 ]

if TYPE_CHECKING:
 from .configuration_unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_unispeech_sat import (
      UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST,
      UniSpeechSatForAudioFrameClassification,
      UniSpeechSatForCTC,
      UniSpeechSatForPreTraining,
      UniSpeechSatForSequenceClassification,
      UniSpeechSatForXVector,
      UniSpeechSatModel,
      UniSpeechSatPreTrainedModel,
  )

else:
 import sys

 __snake_case	:				Union[str, Any]  					=			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



