



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 		UpperCAmelCase    (    snake_case_					):
   SCREAMING_SNAKE_CASE__					      =  42






class 		UpperCAmelCase    (    snake_case_					):





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

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





   def 						__lowerCAmelCase				(						self							,  _lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase      ):
         if latents is None:
               _lowerCAmelCase			      =	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}'''      )
               _lowerCAmelCase			      =	latents.to(_lowerCAmelCase      )

         _lowerCAmelCase			      =	latents * scheduler.init_noise_sigma
         return latents





   def 						__lowerCAmelCase				(						self							,  _lowerCAmelCase=0      ):
         if is_accelerate_available():
               from accelerate import cpu_offload
         else:
               raise ImportError('''Please install accelerate via `pip install accelerate`'''      )

         _lowerCAmelCase			      =	torch.device(F'''cuda:{gpu_id}'''      )

         _lowerCAmelCase			      =	[self.text_encoder, self.prior]
         for cpu_offloaded_model in models:
               if cpu_offloaded_model is not None:
                     cpu_offload(_lowerCAmelCase							,  _lowerCAmelCase      )





   def 						__lowerCAmelCase				(						self							,  _lowerCAmelCase=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.'''      )

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

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

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

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





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

         _lowerCAmelCase			      =	self.text_encoder(text_input_ids.to(_lowerCAmelCase      )      )
         _lowerCAmelCase			      =	text_encoder_output.text_embeds

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

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

         # Rescale the features to have unit variance
         _lowerCAmelCase			      =	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							,  ):

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

         _lowerCAmelCase			      =	self._execution_device

         _lowerCAmelCase			      =	batch_size * num_images_per_prompt

         _lowerCAmelCase			      =	guidance_scale > 1.0
         _lowerCAmelCase			      =	self._encode_prompt(_lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase							,  _lowerCAmelCase      )

         # prior

         self.scheduler.set_timesteps(_lowerCAmelCase							,  device=_lowerCAmelCase      )
         _lowerCAmelCase			      =	self.scheduler.timesteps

         _lowerCAmelCase			      =	self.prior.config.num_embeddings
         _lowerCAmelCase			      =	self.prior.config.embedding_dim

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

               _lowerCAmelCase			      =	self.prior(
                   _lowerCAmelCase							,  timestep=_lowerCAmelCase							,  proj_embedding=_lowerCAmelCase							,  ).predicted_image_embedding

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

               if do_classifier_free_guidance is not None:
                     _lowerCAmelCase      , _lowerCAmelCase			      =	noise_pred.chunk(2      )
                     _lowerCAmelCase			      =	noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

               _lowerCAmelCase			      =	self.scheduler.step(
                   _lowerCAmelCase							,  timestep=_lowerCAmelCase							,  sample=_lowerCAmelCase							,  ).prev_sample

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

         _lowerCAmelCase			      =	[]
         for i, latent in enumerate(_lowerCAmelCase      ):
               _lowerCAmelCase			      =	self.renderer.decode(
                   latent[None, :]							,  _lowerCAmelCase							,  size=_lowerCAmelCase							,  ray_batch_size=4_096							,  n_coarse_samples=64							,  n_fine_samples=128							,  )
               images.append(_lowerCAmelCase      )

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

         _lowerCAmelCase			      =	images.cpu().numpy()

         if output_type == "pil":
               _lowerCAmelCase			      =	[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 math
def 				UpperCAmelCase__		(					_SCREAMING_SNAKE_CASE :						int					)->bool:

      if 1 < number < 4:
            # 2 and 3 are primes
            return True
      elif number < 2 or number % 2 == 0 or number % 3 == 0:
            # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
            return False

      # All primes number are in format of 6k +/- 1
      for i in range(5  ,					int(math.sqrt(_SCREAMING_SNAKE_CASE					) + 1					)  ,					6					):
            if number % i == 0 or number % (i + 2) == 0:
                  return False
      return True
def 				UpperCAmelCase__		(					_SCREAMING_SNAKE_CASE :						int = 6_0_0_8_5_1_4_7_5_1_4_3					)->int:

      try:
            _lowerCAmelCase			      =	int(_SCREAMING_SNAKE_CASE					)
      except (TypeError, ValueError):
            raise TypeError('''Parameter n must be int or castable to int.'''					)
      if n <= 0:
            raise ValueError('''Parameter n must be greater than or equal to one.'''					)
      _lowerCAmelCase			      =	0
      if is_prime(_SCREAMING_SNAKE_CASE					):
            return n
      while n % 2 == 0:
            n //= 2
      if is_prime(_SCREAMING_SNAKE_CASE					):
            return n
      for i in range(3  ,					int(math.sqrt(_SCREAMING_SNAKE_CASE					)					) + 1  ,					2					):
            if n % i == 0:
                  if is_prime(n // i					):
                        _lowerCAmelCase			      =	n // i
                        break
                  elif is_prime(_SCREAMING_SNAKE_CASE					):
                        _lowerCAmelCase			      =	i
      return max_number


if __name__ == "__main__":
    print(F"""{solution() = }""")