



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


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

__lowerCamelCase  				=					'\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 		_snake_case      (			_UpperCAmelCase				):





 """simple docstring"""



 lowerCamelCase_          =			4_2







class 		_snake_case      (			_UpperCAmelCase				):





 """simple docstring"""



 def __init__(						self	,    a	,    a	,    a	,    a	,    a	,    )	->							List[Any]:




   """simple docstring"""







   super().__init__()

   self.register_modules(
       prior=a	,    text_encoder=a	,    tokenizer=a	,    scheduler=a	,    renderer=a	,    )
 def lowercase_		(						self	,    a	,    a	,    a	,    a	,    a	,    a					)	->							Optional[int]:




   """simple docstring"""







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

   _A           =    latents * scheduler.init_noise_sigma
   return latents
 def lowercase_		(						self	,    a=0					)	->							Tuple:




   """simple docstring"""







   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(a	,    a					)
 def lowercase_		(						self	,    a=0					)	->							Any:




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

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

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

   if self.safety_checker is not None:
     _A    ,   _A           =    cpu_offload_with_hook(self.safety_checker	,    a	,    prev_module_hook=a					)

   # We'll offload the last model manually.
   _A           =    hook
 @property
 def lowercase_		(						self					)	->							List[str]:




   """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(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 lowercase_		(						self	,    a	,    a	,    a	,    a	,    )	->							Any:




   """simple docstring"""







   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
   _A           =    0
   # get prompt text embeddings
   _A           =    self.tokenizer(
       a	,    padding='''max_length'''	,    max_length=self.tokenizer.model_max_length	,    truncation=a	,    return_tensors='''pt'''	,    )
   _A           =    text_inputs.input_ids
   _A           =    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					):
     _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(a					)					)
   _A           =    text_encoder_output.text_embeds

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

   if do_classifier_free_guidance:
     _A           =    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
     _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(a					)
 def __call__(						self	,    a	,    a = 1	,    a = 2_5	,    a = None	,    a = None	,    a = 4.0	,    a = 6_4	,    a = "pil"	,    a = True	,    )	->							str:




   """simple docstring"""







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

   _A           =    self._execution_device

   _A           =    batch_size * num_images_per_prompt

   _A           =    guidance_scale > 1.0
   _A           =    self._encode_prompt(a	,    a	,    a	,    a					)

   # prior

   self.scheduler.set_timesteps(a	,    device=a					)
   _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	,    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
   _A           =    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
     _A           =    torch.cat([latents] * 2					) if do_classifier_free_guidance else latents
     _A           =    self.scheduler.scale_model_input(a	,    a					)

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

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

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

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

   _A           =    images.cpu().numpy()

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




def     UpperCAmelCase__ (							__snake_case						,				__snake_case = 1_000							)   -> str:
  if (not isinstance(__snake_case						,				__snake_case							)) or (digit_position <= 0):
    raise ValueError('''Digit position must be a positive integer'''							)
  elif (not isinstance(__snake_case						,				__snake_case							)) or (precision < 0):
    raise ValueError('''Precision must be a nonnegative integer'''							)

  # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
  # accurate
  _A           =    (
      4 * _subsum(__snake_case						,				1						,				__snake_case							)
      - 2 * _subsum(__snake_case						,				4						,				__snake_case							)
      - _subsum(__snake_case						,				5						,				__snake_case							)
      - _subsum(__snake_case						,				6						,				__snake_case							)
  )

  # return the first hex digit of the fractional part of the result
  return hex(int((sum_result % 1) * 16							)							)[2:]




def     UpperCAmelCase__ (							__snake_case						,				__snake_case						,				__snake_case							)   -> float:
  _A           =    0.0
  for sum_index in range(digit_pos_to_extract + precision							):
    _A           =    8 * sum_index + denominator_addend
    if sum_index < digit_pos_to_extract:
      # if the exponential term is an integer and we mod it by the denominator
      # before dividing, only the integer part of the sum will change;
      # the fractional part will not
      _A           =    pow(
          16						,				digit_pos_to_extract - 1 - sum_index						,				__snake_case							)
    else:
      _A           =    pow(16						,				digit_pos_to_extract - 1 - sum_index							)
    total += exponential_term / denominator
  return total


if __name__ == "__main__":
    import doctest

    doctest.testmod()