

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_     =       logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase_     =       '\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 			__lowerCAmelCase					( SCREAMING_SNAKE_CASE							):
  _a						      =  42





class 			__lowerCAmelCase					( SCREAMING_SNAKE_CASE							):




  def __init__(    self							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       )  ->			Tuple:
        '''simple docstring'''






        super().__init__()

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




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase )  ->			str:
        '''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   A__					(    self							,       lowerCAmelCase=0 )  ->			Dict:
        '''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.text_encoder, self.prior]
        for cpu_offloaded_model in models:
              if cpu_offloaded_model is not None:
                    cpu_offload(lowerCAmelCase							,       lowerCAmelCase )




  def   A__					(    self							,       lowerCAmelCase=0 )  ->			Optional[int]:
        '''simple docstring'''






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

        _lowercase     	=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)

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

        if self.safety_checker is not None:
              _lowercase	,	_lowercase     	=cpu_offload_with_hook(self.safety_checker							,       lowerCAmelCase							,       prev_module_hook=lowerCAmelCase )

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




  @property
  def   A__					(    self )  ->			Dict:
        '''simple docstring'''






        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							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase							,       )  ->			Optional[Any]:
        '''simple docstring'''






        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
        _lowercase     	=0
        # get prompt text embeddings
        _lowercase     	=self.tokenizer(
            lowerCAmelCase							,       padding='max_length'							,       max_length=self.tokenizer.model_max_length							,       truncation=lowerCAmelCase							,       return_tensors='pt'							,       )
        _lowercase     	=text_inputs.input_ids
        _lowercase     	=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 ):
              _lowercase     	=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}''' )

        _lowercase     	=self.text_encoder(text_input_ids.to(lowerCAmelCase ) )
        _lowercase     	=text_encoder_output.text_embeds

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

        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_prompt_embeds, prompt_embeds] )

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

        return prompt_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							,       )  ->			Dict:
        '''simple docstring'''






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

        _lowercase     	=self._execution_device

        _lowercase     	=batch_size * num_images_per_prompt

        _lowercase     	=guidance_scale > 1.0
        _lowercase     	=self._encode_prompt(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)							,       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
        _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 ):
              _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 )





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


lowercase_     =       {
    'configuration_oneformer': ['ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OneFormerConfig'],
    'processing_oneformer': ['OneFormerProcessor'],
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_     =       ['OneFormerImageProcessor']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_     =       [
      'ONEFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
      'OneFormerForUniversalSegmentation',
      'OneFormerModel',
      'OneFormerPreTrainedModel',
  ]

if TYPE_CHECKING:
  from .configuration_oneformer import ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, OneFormerConfig
  from .processing_oneformer import OneFormerProcessor

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_oneformer import OneFormerImageProcessor
  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_oneformer import (
        ONEFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
        OneFormerForUniversalSegmentation,
        OneFormerModel,
        OneFormerPreTrainedModel,
    )


else:
  import sys

  lowercase_     =       _LazyModule(__name__, globals()['__file__'], _import_structure)


