

"""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


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

_a					 =				'\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    (      lowercase  ):







 """simple docstring"""







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







class    _lowerCAmelCase    (      lowercase  ):







 """simple docstring"""







 def __init__(     self				:     Any,   UpperCAmelCase__				:     PriorTransformer,   UpperCAmelCase__				:     CLIPTextModelWithProjection,   UpperCAmelCase__				:     CLIPTokenizer,   UpperCAmelCase__				:     HeunDiscreteScheduler,   UpperCAmelCase__				:     ShapERenderer,   ):
    super().__init__()

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


 def    _lowercase					(     self				:     List[Any],   UpperCAmelCase__				:     Optional[Any],   UpperCAmelCase__				:     Union[str, Any],   UpperCAmelCase__				:     int,   UpperCAmelCase__				:     Optional[int],   UpperCAmelCase__				:     Tuple,   UpperCAmelCase__				:     str      ):
    if latents is None:
       __lowercase								=		randn_tensor(UpperCAmelCase__,   generator=UpperCAmelCase__,   device=UpperCAmelCase__,   dtype=UpperCAmelCase__      )
    else:
       if latents.shape != shape:
          raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""      )
       __lowercase								=		latents.to(UpperCAmelCase__      )

    __lowercase								=		latents * scheduler.init_noise_sigma
    return latents


 def    _lowercase					(     self				:     List[str],   UpperCAmelCase__				:     List[Any]=0      ):
    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(UpperCAmelCase__,   UpperCAmelCase__      )


 def    _lowercase					(     self				:     List[str],   UpperCAmelCase__				:     List[Any]=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."      )

    __lowercase								=		torch.device(F"""cuda:{gpu_id}"""      )

    if self.device.type != "cpu":
       self.to("cpu",   silence_dtype_warnings=UpperCAmelCase__      )
       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(UpperCAmelCase__,   UpperCAmelCase__,   prev_module_hook=UpperCAmelCase__      )

    if self.safety_checker is not None:
       __lowercase						,__lowercase								=		cpu_offload_with_hook(self.safety_checker,   UpperCAmelCase__,   prev_module_hook=UpperCAmelCase__      )

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


 @property
 def    _lowercase					(     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(UpperCAmelCase__,   "_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				:     List[Any],   UpperCAmelCase__				:     List[str],   UpperCAmelCase__				:     Optional[Any],   UpperCAmelCase__				:     Tuple,   UpperCAmelCase__				:     Optional[int],   ):
    len(UpperCAmelCase__      ) if isinstance(UpperCAmelCase__,   UpperCAmelCase__      ) 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(
        UpperCAmelCase__,   padding="max_length",   max_length=self.tokenizer.model_max_length,   truncation=UpperCAmelCase__,   return_tensors="pt",   )
    __lowercase								=		text_inputs.input_ids
    __lowercase								=		self.tokenizer(UpperCAmelCase__,   padding="longest",   return_tensors="pt"      ).input_ids

    if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCAmelCase__,   UpperCAmelCase__      ):
       __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(UpperCAmelCase__      )      )
    __lowercase								=		text_encoder_output.text_embeds

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

    if do_classifier_free_guidance:
       __lowercase								=		torch.zeros_like(UpperCAmelCase__      )

       # 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(UpperCAmelCase__      )
 def __call__(     self				:     str,   UpperCAmelCase__				:     str,   UpperCAmelCase__				:     int = 1,   UpperCAmelCase__				:     int = 2_5,   UpperCAmelCase__				:     Optional[Union[torch.Generator, List[torch.Generator]]] = None,   UpperCAmelCase__				:     Optional[torch.FloatTensor] = None,   UpperCAmelCase__				:     float = 4.0,   UpperCAmelCase__				:     int = 6_4,   UpperCAmelCase__				:     Optional[str] = "pil",   UpperCAmelCase__				:     bool = True,   ):

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

    __lowercase								=		self._execution_device

    __lowercase								=		batch_size * num_images_per_prompt

    __lowercase								=		guidance_scale > 1.0
    __lowercase								=		self._encode_prompt(UpperCAmelCase__,   UpperCAmelCase__,   UpperCAmelCase__,   UpperCAmelCase__      )

    # prior

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

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

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

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

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

    __lowercase								=		torch.stack(UpperCAmelCase__      )

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







"""simple docstring"""





def     _A    (    UpperCamelCase_	:			str)      ->		int:
   '''simple docstring'''


   __lowercase								=		0
   for plain_chr in plain_text:
      __lowercase								=		(
          ord(UpperCamelCase_) + (hash_value << 6) + (hash_value << 16) - hash_value
      )
   return hash_value




