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


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

__UpperCAmelCase												=   "\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 		_a     (							__lowerCAmelCase  ):







   """simple docstring"""




   A		= 42



class 		_a     (							__lowerCAmelCase  ):







   """simple docstring"""




   def __init__(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,):
    super().__init__()

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






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      ):






    if latents is None:
     SCREAMING_SNAKE_CASE  :  Any								=		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}"""      )
     SCREAMING_SNAKE_CASE  :  Dict								=		latents.to(lowerCamelCase__      )

    SCREAMING_SNAKE_CASE  :  Optional[int]								=		latents * scheduler.init_noise_sigma
    return latents






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE=0      ):






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

    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		torch.device(f"""cuda:{gpu_id}"""      )

    SCREAMING_SNAKE_CASE  :  Tuple								=		[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    ,__SCREAMING_SNAKE_CASE=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.'      )

    SCREAMING_SNAKE_CASE  :  str								=		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)

    SCREAMING_SNAKE_CASE  :  List[str]								=		None
    for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
     SCREAMING_SNAKE_CASE  :  Dict								=		cpu_offload_with_hook(lowerCamelCase__    ,lowerCamelCase__    ,prev_module_hook=lowerCamelCase__      )

    if self.safety_checker is not None:
     SCREAMING_SNAKE_CASE  :  List[Any]								=		cpu_offload_with_hook(self.safety_checker    ,lowerCamelCase__    ,prev_module_hook=lowerCamelCase__      )

    # We'll offload the last model manually.
    SCREAMING_SNAKE_CASE  :  List[str]								=		hook






   @property
   def 					__a			(       self      ):






    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    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,):
    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
    SCREAMING_SNAKE_CASE  :  Dict								=		0
    # get prompt text embeddings
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		self.tokenizer(
        lowerCamelCase__    ,padding='max_length'    ,max_length=self.tokenizer.model_max_length    ,truncation=lowerCamelCase__    ,return_tensors='pt'    ,)
    SCREAMING_SNAKE_CASE  :  Optional[int]								=		text_inputs.input_ids
    SCREAMING_SNAKE_CASE  :  Any								=		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__      ):
     SCREAMING_SNAKE_CASE  :  List[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}"""      )

    SCREAMING_SNAKE_CASE  :  Optional[int]								=		self.text_encoder(text_input_ids.to(lowerCamelCase__      )      )
    SCREAMING_SNAKE_CASE  :  Dict								=		text_encoder_output.text_embeds

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

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

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

    return prompt_embeds






   @torch.no_grad()
   @replace_example_docstring(lowerCamelCase__      )
   def __call__(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE = 1    ,__SCREAMING_SNAKE_CASE = 25    ,__SCREAMING_SNAKE_CASE = None    ,__SCREAMING_SNAKE_CASE = None    ,__SCREAMING_SNAKE_CASE = 4.0    ,__SCREAMING_SNAKE_CASE = 64    ,__SCREAMING_SNAKE_CASE = "pil"    ,__SCREAMING_SNAKE_CASE = True    ,):






    if isinstance(lowerCamelCase__    ,lowerCamelCase__      ):
     SCREAMING_SNAKE_CASE  :  Dict								=		1
    elif isinstance(lowerCamelCase__    ,lowerCamelCase__      ):
     SCREAMING_SNAKE_CASE  :  List[str]								=		len(lowerCamelCase__      )
    else:
     raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase__      )}"""      )

    SCREAMING_SNAKE_CASE  :  Any								=		self._execution_device

    SCREAMING_SNAKE_CASE  :  Optional[int]								=		batch_size * num_images_per_prompt

    SCREAMING_SNAKE_CASE  :  Any								=		guidance_scale > 1.0
    SCREAMING_SNAKE_CASE  :  Any								=		self._encode_prompt(lowerCamelCase__    ,lowerCamelCase__    ,lowerCamelCase__    ,lowerCamelCase__      )

    # prior

    self.scheduler.set_timesteps(lowerCamelCase__    ,device=lowerCamelCase__      )
    SCREAMING_SNAKE_CASE  :  Any								=		self.scheduler.timesteps

    SCREAMING_SNAKE_CASE  :  List[Any]								=		self.prior.config.num_embeddings
    SCREAMING_SNAKE_CASE  :  List[str]								=		self.prior.config.embedding_dim

    SCREAMING_SNAKE_CASE  :  Tuple								=		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
    SCREAMING_SNAKE_CASE  :  Any								=		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
     SCREAMING_SNAKE_CASE  :  Optional[Any]								=		torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		self.scheduler.scale_model_input(lowerCamelCase__    ,lowerCamelCase__      )

     SCREAMING_SNAKE_CASE  :  Optional[Any]								=		self.prior(
         lowerCamelCase__    ,timestep=lowerCamelCase__    ,proj_embedding=lowerCamelCase__    ,).predicted_image_embedding

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

     if do_classifier_free_guidance is not None:
      SCREAMING_SNAKE_CASE  :  Optional[int]								=		noise_pred.chunk(2      )
      SCREAMING_SNAKE_CASE  :  str								=		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		self.scheduler.step(
         lowerCamelCase__    ,timestep=lowerCamelCase__    ,sample=lowerCamelCase__    ,).prev_sample

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

    SCREAMING_SNAKE_CASE  :  Tuple								=		[]
    for i, latent in enumerate(lowerCamelCase__      ):
     SCREAMING_SNAKE_CASE  :  Tuple								=		self.renderer.decode(
         latent[None, :]    ,lowerCamelCase__    ,size=lowerCamelCase__    ,ray_batch_size=4096    ,n_coarse_samples=64    ,n_fine_samples=128    ,)
     images.append(lowerCamelCase__      )

    SCREAMING_SNAKE_CASE  :  List[Any]								=		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}"""      )

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

    if output_type == "pil":
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		[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__      )






import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__UpperCamelCase							:							Optional[Any]    							=					"src/transformers"

# Matches is_xxx_available()
__UpperCamelCase							:							str    							=					re.compile(r"is\_([a-z_]*)_available()")
# Matches from xxx import bla
__UpperCamelCase							:							Union[str, Any]    							=					re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
__UpperCamelCase							:							Dict    							=					re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)")


__UpperCamelCase							:							Any    							=					"\n{0} = None\n"

__UpperCamelCase							:							Tuple    							=					"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"


__UpperCamelCase							:							Optional[Any]    							=					"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"

def       _a	(					SCREAMING_SNAKE_CASE						:					str  ):







 """simple docstring"""



 if _re_test_backend.search(SCREAMING_SNAKE_CASE  ) is None:
  return None
 UpperCamelCase__       :     List[str] 							= [b[0] for b in _re_backend.findall(SCREAMING_SNAKE_CASE  )]
 backends.sort()
 return "_and_".join(SCREAMING_SNAKE_CASE  )

def       _a	(					):







 """simple docstring"""



 with open(os.path.join(SCREAMING_SNAKE_CASE     ,			'''__init__.py'''  )     ,			'''r'''     ,			encoding='''utf-8'''     ,			newline='''\n'''  ) as f:
  UpperCamelCase__       :     Union[str, Any] 							= f.readlines()

 # Get to the point we do the actual imports for type checking
 UpperCamelCase__       :     int 							= 0
 while not lines[line_index].startswith('''if TYPE_CHECKING'''  ):
  line_index += 1

 UpperCamelCase__       :     Optional[Any] 							= {}
 # Go through the end of the file
 while line_index < len(SCREAMING_SNAKE_CASE  ):
  # If the line is an if is_backend_available, we grab all objects associated.
  UpperCamelCase__       :     Any 							= find_backend(lines[line_index]  )
  if backend is not None:
   while not lines[line_index].startswith('''    else:'''  ):
    line_index += 1
   line_index += 1

   UpperCamelCase__       :     List[str] 							= []
   # Until we unindent, add backend objects to the list
   while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(''' ''' * 8  ):
    UpperCamelCase__       :     str 							= lines[line_index]
    UpperCamelCase__       :     Union[str, Any] 							= _re_single_line_import.search(SCREAMING_SNAKE_CASE  )
    if single_line_import_search is not None:
     objects.extend(single_line_import_search.groups()[0].split(''', '''  )  )
    elif line.startswith(''' ''' * 12  ):
     objects.append(line[12:-2]  )
    line_index += 1

   UpperCamelCase__       :     Optional[int] 							= objects
  else:
   line_index += 1

 return backend_specific_objects

def       _a	(					SCREAMING_SNAKE_CASE						:					str     ,			SCREAMING_SNAKE_CASE						:					List[str]  ):







 """simple docstring"""



 if name.isupper():
  return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE  )
 elif name.islower():
  return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  )
 else:
  return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  )

def       _a	(					SCREAMING_SNAKE_CASE						:					Dict=None  ):







 """simple docstring"""



 if backend_specific_objects is None:
  UpperCamelCase__       :     Any 							= read_init()
 # For special correspondence backend to module name as used in the function requires_modulename
 UpperCamelCase__       :     Optional[Any] 							= {}

 for backend, objects in backend_specific_objects.items():
  UpperCamelCase__       :     int 							= '''[''' + ''', '''.join(F"\"{b}\"" for b in backend.split('''_and_'''  )  ) + ''']'''
  UpperCamelCase__       :     Any 							= '''# This file is autogenerated by the command `make fix-copies`, do not edit.\n'''
  dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
  dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  ) for o in objects]  )
  UpperCamelCase__       :     List[str] 							= dummy_file

 return dummy_files

def       _a	(					SCREAMING_SNAKE_CASE						:					Union[str, Any]=False  ):







 """simple docstring"""



 UpperCamelCase__       :     Dict 							= create_dummy_files()
 # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
 UpperCamelCase__       :     Tuple 							= {'''torch''': '''pt'''}

 # Locate actual dummy modules and read their content.
 UpperCamelCase__       :     Optional[Any] 							= os.path.join(SCREAMING_SNAKE_CASE     ,			'''utils'''  )
 UpperCamelCase__       :     int 							= {
     backend: os.path.join(SCREAMING_SNAKE_CASE     ,			F"dummy_{short_names.get(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  )}_objects.py"  )
     for backend in dummy_files.keys()
 }

 UpperCamelCase__       :     Optional[Any] 							= {}
 for backend, file_path in dummy_file_paths.items():
  if os.path.isfile(SCREAMING_SNAKE_CASE  ):
   with open(SCREAMING_SNAKE_CASE     ,			'''r'''     ,			encoding='''utf-8'''     ,			newline='''\n'''  ) as f:
    UpperCamelCase__       :     List[Any] 							= f.read()
  else:
   UpperCamelCase__       :     List[Any] 							= ''''''

 for backend in dummy_files.keys():
  if dummy_files[backend] != actual_dummies[backend]:
   if overwrite:
    print(
        F"Updating transformers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  )}_objects.py as the main "
        '''__init__ has new objects.'''  )
    with open(dummy_file_paths[backend]     ,			'''w'''     ,			encoding='''utf-8'''     ,			newline='''\n'''  ) as f:
     f.write(dummy_files[backend]  )
   else:
    raise ValueError(
        '''The main __init__ has objects that are not present in '''
        F"transformers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE     ,			SCREAMING_SNAKE_CASE  )}_objects.py. Run `make fix-copies` "
        '''to fix this.'''  )


if __name__ == "__main__":
       __UpperCamelCase							:							Optional[int]    							=					argparse.ArgumentParser()
       parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
       __UpperCamelCase							:							str    							=					parser.parse_args()

       check_dummies(args.fix_and_overwrite)


