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

a__		: str  							=							"\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__	(     SCREAMING_SNAKE_CASE):
 UpperCAmelCase__     :     Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]


class 			UpperCamelCase__	(     SCREAMING_SNAKE_CASE):






 def __init__(      self	:List[Any]						,					_A	:PriorTransformer						,					_A	:CLIPTextModelWithProjection						,					_A	:CLIPTokenizer						,					_A	:HeunDiscreteScheduler						,					_A	:ShapERenderer						,					)					->      Tuple:







       '''simple docstring'''



       super().__init__()

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






 def 						lowercase_    (      self	:Any						,					_A	:Any						,					_A	:int						,					_A	:List[Any]						,					_A	:Optional[int]						,					_A	:Optional[int]						,					_A	:Any      )					->      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	:Optional[int]						,					_A	:int=0      )					->      Optional[Any]:







       '''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	:Tuple						,					_A	:Optional[int]=0      )					->      List[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	:Dict      )					->      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	:Tuple						,					_A	:List[str]						,					_A	:str						,					_A	:Union[str, Any]						,					_A	:List[str]						,					)					->      Tuple:







       '''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	:Optional[Any]						,					_A	:str						,					_A	:int = 1						,					_A	:int = 25						,					_A	:Optional[Union[torch.Generator, List[torch.Generator]]] = None						,					_A	:Optional[torch.FloatTensor] = None						,					_A	:float = 4.0						,					_A	:int = 64						,					_A	:Optional[str] = "pil"						,					_A	:bool = True						,					)					->      List[Any]:







       '''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_096						,					n_coarse_samples=64						,					n_fine_samples=128						,					)
             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      )








'''simple docstring'''





class 			UpperCamelCase__	:






 def __init__(      self	:Optional[Any]						,					_A	:Tuple      )					->      Tuple:







       '''simple docstring'''



       __A													=      data
       __A													=      None
       __A													=      None






 def __str__(      self	:List[str]      )					->      Optional[int]:







       '''simple docstring'''



       return F'{self.data}'


class 			UpperCamelCase__	:






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







       '''simple docstring'''



       __A													=      None
       __A													=      None






 def __iter__(      self	:Optional[int]      )					->      List[Any]:







       '''simple docstring'''



       __A													=      self.head
       while node:
             yield node.data
             __A													=      node.next






 def __str__(      self	:Dict      )					->      Union[str, Any]:







       '''simple docstring'''



       return "->".join([str(_A      ) for item in self]      )






 def __len__(      self	:int      )					->      List[str]:







       '''simple docstring'''



       return sum(1 for _ in self      )






 def 						lowercase_    (      self	:List[str]						,					_A	:Any      )					->      str:







       '''simple docstring'''



       self.insert_at_nth(0						,					_A      )






 def 						lowercase_    (      self	:Dict						,					_A	:Optional[Any]      )					->      Tuple:







       '''simple docstring'''



       self.insert_at_nth(len(self      )						,					_A      )






 def 						lowercase_    (      self	:Optional[int]						,					_A	:int						,					_A	:Optional[int]      )					->      int:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length:
             raise IndexError('list index out of range'      )
       __A													=      Node(_A      )
       if self.head is None:
             __A													=      __A													=      new_node
       elif index == 0:
             __A													=      new_node
             __A													=      self.head
             __A													=      new_node
       elif index == length:
             __A													=      new_node
             __A													=      self.tail
             __A													=      new_node
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      new_node
             __A													=      temp.previous
             __A													=      temp
             __A													=      new_node






 def 						lowercase_    (      self	:Optional[int]      )					->      List[str]:







       '''simple docstring'''



       return self.delete_at_nth(0      )






 def 						lowercase_    (      self	:Any      )					->      Tuple:







       '''simple docstring'''



       return self.delete_at_nth(len(self      ) - 1      )






 def 						lowercase_    (      self	:Dict						,					_A	:int      )					->      List[str]:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length - 1:
             raise IndexError('list index out of range'      )
       __A													=      self.head  # default first node
       if length == 1:
             __A													=      __A													=      None
       elif index == 0:
             __A													=      self.head.next
             __A													=      None
       elif index == length - 1:
             __A													=      self.tail
             __A													=      self.tail.previous
             __A													=      None
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      temp
             __A													=      temp.previous
             __A													=      temp.next
       return delete_node.data






 def 						lowercase_    (      self	:List[str]						,					_A	:Dict      )					->      str:







       '''simple docstring'''



       __A													=      self.head

       while current.data != data:  # Find the position to delete
             if current.next:
                   __A													=      current.next
             else:  # We have reached the end an no value matches
                   raise ValueError('No data matching given value'      )

       if current == self.head:
             self.delete_head()

       elif current == self.tail:
             self.delete_tail()

       else:  # Before: 1 <--> 2(current) <--> 3
             __A													=      current.next  # 1 --> 3
             __A													=      current.previous  # 1 <--> 3
       return data






 def 						lowercase_    (      self	:List[str]      )					->      Tuple:







       '''simple docstring'''



       return len(self      ) == 0





def 							snake_case				(		)->      None:







      """simple docstring"""
      __A													=      DoublyLinkedList()
      assert linked_list.is_empty() is True
      assert str(UpperCAmelCase						) == ""

      try:
            linked_list.delete_head()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      try:
            linked_list.delete_tail()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      for i in range(1_0						):
            assert len(UpperCAmelCase						) == i
            linked_list.insert_at_nth(UpperCAmelCase   ,	i + 1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_1						)						)

      linked_list.insert_at_head(0						)
      linked_list.insert_at_tail(1_1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(0   ,	1_2						)						)

      assert linked_list.delete_head() == 0
      assert linked_list.delete_at_nth(9						) == 1_0
      assert linked_list.delete_tail() == 1_1
      assert len(UpperCAmelCase						) == 9
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_0						)						)


if __name__ == "__main__":
 from doctest import testmod

 testmod()






