





from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__lowerCamelCase       :     Any   =     """
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""



@dataclass
class 					A__   (       __snake_case			):
      _UpperCAmelCase	:Union[PIL.Image.Image, np.ndarray]



class 					A__   (       __snake_case			):





      def __init__( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       super().__init__()

       self.register_modules(
           prior=A_       ,							image_encoder=A_       ,							image_processor=A_       ,							scheduler=A_       ,							renderer=A_       ,							)





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_   ):
       '''simple docstring'''




       if latents is None:
        UpperCamelCase	:					str       	=   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}"""   )
        UpperCamelCase	:					Dict       	=   latents.to(A_   )

       UpperCamelCase	:					Tuple       	=   latents * scheduler.init_noise_sigma
       return latents





      def        __UpperCamelCase( self       ,							A_=0   ):
       '''simple docstring'''




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

       UpperCamelCase	:					List[Any]       	=   torch.device(F"""cuda:{gpu_id}"""   )

       UpperCamelCase	:					int       	=   [self.image_encoder, self.prior]
       for cpu_offloaded_model in models:
        if cpu_offloaded_model is not None:
         cpu_offload(A_       ,							A_   )





      @property
      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       if self.device != torch.device("meta"   ) or not hasattr(self.image_encoder       ,							"_hf_hook"   ):
        return self.device
       for module in self.image_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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       if isinstance(A_       ,							A_   ) and isinstance(image[0]       ,							torch.Tensor   ):
        UpperCamelCase	:					Any       	=   torch.cat(A_       ,							axis=0   ) if image[0].ndim == 4 else torch.stack(A_       ,							axis=0   )

       if not isinstance(A_       ,							torch.Tensor   ):
        UpperCamelCase	:					Dict       	=   self.image_processor(A_       ,							return_tensors="pt"   ).pixel_values[0].unsqueeze(0   )

       UpperCamelCase	:					str       	=   image.to(dtype=self.image_encoder.dtype       ,							device=A_   )

       UpperCamelCase	:					Union[str, Any]       	=   self.image_encoder(A_   )["last_hidden_state"]
       UpperCamelCase	:					Union[str, Any]       	=   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       UpperCamelCase	:					Dict       	=   image_embeds.repeat_interleave(A_       ,							dim=0   )

       if do_classifier_free_guidance:
        UpperCamelCase	:					List[str]       	=   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
        UpperCamelCase	:					Dict       	=   torch.cat([negative_image_embeds, image_embeds]   )

       return image_embeds





      @torch.no_grad()
      @replace_example_docstring(A_   )
      def __call__( self       ,							A_       ,							A_ = 1       ,							A_ = 25       ,							A_ = None       ,							A_ = None       ,							A_ = 4.0       ,							A_ = 64       ,							A_ = "pil"       ,							A_ = True       ,							):
       '''simple docstring'''




       if isinstance(A_       ,							PIL.Image.Image   ):
        UpperCamelCase	:					Union[str, Any]       	=   1
       elif isinstance(A_       ,							torch.Tensor   ):
        UpperCamelCase	:					str       	=   image.shape[0]
       elif isinstance(A_       ,							A_   ) and isinstance(image[0]       ,							(torch.Tensor, PIL.Image.Image)   ):
        UpperCamelCase	:					Optional[Any]       	=   len(A_   )
       else:
        raise ValueError(
            F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(A_   )}"""   )

       UpperCamelCase	:					Dict       	=   self._execution_device

       UpperCamelCase	:					Dict       	=   batch_size * num_images_per_prompt

       UpperCamelCase	:					str       	=   guidance_scale > 1.0
       UpperCamelCase	:					str       	=   self._encode_image(A_       ,							A_       ,							A_       ,							A_   )

       # prior

       self.scheduler.set_timesteps(A_       ,							device=A_   )
       UpperCamelCase	:					Optional[Any]       	=   self.scheduler.timesteps

       UpperCamelCase	:					List[str]       	=   self.prior.config.num_embeddings
       UpperCamelCase	:					Union[str, Any]       	=   self.prior.config.embedding_dim

       UpperCamelCase	:					int       	=   self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)       ,							image_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
       UpperCamelCase	:					Optional[int]       	=   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
        UpperCamelCase	:					Union[str, Any]       	=   torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
        UpperCamelCase	:					List[str]       	=   self.scheduler.scale_model_input(A_       ,							A_   )

        UpperCamelCase	:					List[str]       	=   self.prior(
            A_       ,							timestep=A_       ,							proj_embedding=A_       ,							).predicted_image_embedding

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

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

        UpperCamelCase	:					Optional[int]       	=   self.scheduler.step(
            A_       ,							timestep=A_       ,							sample=A_       ,							).prev_sample

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

       UpperCamelCase	:					Any       	=   []
       for i, latent in enumerate(A_   ):
        print()
        UpperCamelCase	:					Union[str, Any]       	=   self.renderer.decode(
            latent[None, :]       ,							A_       ,							size=A_       ,							ray_batch_size=4096       ,							n_coarse_samples=64       ,							n_fine_samples=128       ,							)

        images.append(A_   )

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

       UpperCamelCase	:					str       	=   images.cpu().numpy()

       if output_type == "pil":
        UpperCamelCase	:					List[str]       	=   [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_   )







from math import sqrt



def 		A_				(     _lowerCAmelCase     )						-> bool:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     number >= 0
 ), "'number' must been an int and positive"

 UpperCamelCase	:					List[Any]       	=   True

 # 0 and 1 are none primes.
 if number <= 1:
  UpperCamelCase	:					List[Any]       	=   False

 for divisor in range(2							,   int(round(sqrt(_lowerCAmelCase     )     )     ) + 1     ):
  # if 'number' divisible by 'divisor' then sets 'status'
  # of false and break up the loop.
  if number % divisor == 0:
   UpperCamelCase	:					Union[str, Any]       	=   False
   break

    # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'status' must been from type bool"

 return status



def 		A_				(     _lowerCAmelCase     )						-> Any:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n > 2), "'N' must been an int and > 2"

 # beginList: contains all natural numbers from 2 up to N
 UpperCamelCase	:					int       	=   list(range(2							,   n + 1     )     )

 UpperCamelCase	:					Optional[int]       	=   []  # this list will be returns.

 # actual sieve of erathostenes
 for i in range(len(_lowerCAmelCase     )     ):
  for j in range(i + 1							,   len(_lowerCAmelCase     )     ):
   if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
    UpperCamelCase	:					Tuple       	=   0

    # filters actual prime numbers.
 UpperCamelCase	:					str       	=   [x for x in begin_list if x != 0]

 # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'ans' must been from type list"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Optional[Any]:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n > 2), "'N' must been an int and > 2"

 UpperCamelCase	:					str       	=   []

 # iterates over all numbers between 2 up to N+1
 # if a number is prime then appends to list 'ans'
 for number in range(2							,   n + 1     ):
  if is_prime(_lowerCAmelCase     ):
   ans.append(_lowerCAmelCase     )

    # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'ans' must been from type list"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Any:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and number >= 0, "'number' must been an int and >= 0"

 UpperCamelCase	:					Optional[Any]       	=   []  # this list will be returns of the function.

 # potential prime number factors.

 UpperCamelCase	:					Tuple       	=   2

 UpperCamelCase	:					str       	=   number

 if number == 0 or number == 1:
  ans.append(_lowerCAmelCase     )

 # if 'number' not prime then builds the prime factorization of 'number'
 elif not is_prime(_lowerCAmelCase     ):
  while quotient != 1:
   if is_prime(_lowerCAmelCase     ) and (quotient % factor == 0):
    ans.append(_lowerCAmelCase     )
    quotient /= factor
   else:
    factor += 1

 else:
  ans.append(_lowerCAmelCase     )

 # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'ans' must been from type list"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Any:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     number >= 0
 ), "'number' bust been an int and >= 0"

 UpperCamelCase	:					List[Any]       	=   0

 # prime factorization of 'number'
 UpperCamelCase	:					Any       	=   prime_factorization(_lowerCAmelCase     )

 UpperCamelCase	:					List[Any]       	=   max(_lowerCAmelCase     )

 # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'ans' must been from type int"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Union[str, Any]:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     number >= 0
 ), "'number' bust been an int and >= 0"

 UpperCamelCase	:					List[Any]       	=   0

 # prime factorization of 'number'
 UpperCamelCase	:					Dict       	=   prime_factorization(_lowerCAmelCase     )

 UpperCamelCase	:					List[Any]       	=   min(_lowerCAmelCase     )

 # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'ans' must been from type int"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Optional[Any]:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'number' must been an int"
 assert isinstance(number % 2 == 0							,   _lowerCAmelCase     ), "compare bust been from type bool"

 return number % 2 == 0



def 		A_				(     _lowerCAmelCase     )						-> List[Any]:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ), "'number' must been an int"
 assert isinstance(number % 2 != 0							,   _lowerCAmelCase     ), "compare bust been from type bool"

 return number % 2 != 0



def 		A_				(     _lowerCAmelCase     )						-> Any:
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (number > 2) and is_even(_lowerCAmelCase     )
 ), "'number' must been an int, even and > 2"

 UpperCamelCase	:					List[str]       	=   []  # this list will returned

 # creates a list of prime numbers between 2 up to 'number'
 UpperCamelCase	:					Dict       	=   get_prime_numbers(_lowerCAmelCase     )
 UpperCamelCase	:					Tuple       	=   len(_lowerCAmelCase     )

 # run variable for while-loops.
 UpperCamelCase	:					Optional[int]       	=   0
 UpperCamelCase	:					int       	=   None

 # exit variable. for break up the loops
 UpperCamelCase	:					Union[str, Any]       	=   True

 while i < len_pn and loop:
  UpperCamelCase	:					Tuple       	=   i + 1

  while j < len_pn and loop:
   if prime_numbers[i] + prime_numbers[j] == number:
    UpperCamelCase	:					Any       	=   False
    ans.append(prime_numbers[i]     )
    ans.append(prime_numbers[j]     )

   j += 1

  i += 1

 # precondition
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (len(_lowerCAmelCase     ) == 2)
     and (ans[0] + ans[1] == number)
     and is_prime(ans[0]     )
     and is_prime(ans[1]     )
 ), "'ans' must contains two primes. And sum of elements must been eq 'number'"

 return ans



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> str:
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (numbera >= 0)
     and (numbera >= 0)
 ), "'number1' and 'number2' must been positive integer."

 UpperCamelCase	:					Tuple       	=   0

 while numbera != 0:
  UpperCamelCase	:					Tuple       	=   numbera % numbera
  UpperCamelCase	:					Any       	=   numbera
  UpperCamelCase	:					Union[str, Any]       	=   rest

 # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     numbera >= 0
 ), "'number' must been from type int and positive"

 return numbera



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> int:
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (numbera >= 1)
     and (numbera >= 1)
 ), "'number1' and 'number2' must been positive integer."

 UpperCamelCase	:					Optional[int]       	=   1  # actual answer that will be return.

 # for kgV (x,1)
 if numbera > 1 and numbera > 1:
  # builds the prime factorization of 'number1' and 'number2'
  UpperCamelCase	:					List[Any]       	=   prime_factorization(_lowerCAmelCase     )
  UpperCamelCase	:					Union[str, Any]       	=   prime_factorization(_lowerCAmelCase     )

 elif numbera == 1 or numbera == 1:
  UpperCamelCase	:					Optional[Any]       	=   []
  UpperCamelCase	:					int       	=   []
  UpperCamelCase	:					List[Any]       	=   max(_lowerCAmelCase							,   _lowerCAmelCase     )

 UpperCamelCase	:					Optional[int]       	=   0
 UpperCamelCase	:					Tuple       	=   0

 UpperCamelCase	:					List[str]       	=   []  # captured numbers int both 'primeFac1' and 'primeFac2'

 # iterates through primeFac1
 for n in prime_fac_a:
  if n not in done:
   if n in prime_fac_a:
    UpperCamelCase	:					str       	=   prime_fac_a.count(_lowerCAmelCase     )
    UpperCamelCase	:					Tuple       	=   prime_fac_a.count(_lowerCAmelCase     )

    for _ in range(max(_lowerCAmelCase							,   _lowerCAmelCase     )     ):
     ans *= n

   else:
    UpperCamelCase	:					str       	=   prime_fac_a.count(_lowerCAmelCase     )

    for _ in range(_lowerCAmelCase     ):
     ans *= n

   done.append(_lowerCAmelCase     )

    # iterates through primeFac2
 for n in prime_fac_a:
  if n not in done:
   UpperCamelCase	:					Any       	=   prime_fac_a.count(_lowerCAmelCase     )

   for _ in range(_lowerCAmelCase     ):
    ans *= n

   done.append(_lowerCAmelCase     )

    # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     ans >= 0
 ), "'ans' must been from type int and positive"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Tuple:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n >= 0), "'number' must been a positive int"

 UpperCamelCase	:					int       	=   0
 UpperCamelCase	:					int       	=   2  # this variable holds the answer

 while index < n:
  index += 1

  ans += 1  # counts to the next number

  # if ans not prime then
  # runs to the next prime number.
  while not is_prime(_lowerCAmelCase     ):
   ans += 1

    # precondition
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and is_prime(
     _lowerCAmelCase     ), "'ans' must been a prime number and from type int"

 return ans



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> int:
 assert (
     is_prime(_lowerCAmelCase     ) and is_prime(_lowerCAmelCase     ) and (p_number_a < p_number_a)
 ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"

 UpperCamelCase	:					str       	=   p_number_a + 1  # jump to the next number

 UpperCamelCase	:					Dict       	=   []  # this list will be returns.

 # if number is not prime then
 # fetch the next prime number.
 while not is_prime(_lowerCAmelCase     ):
  number += 1

 while number < p_number_a:
  ans.append(_lowerCAmelCase     )

  number += 1

  # fetch the next prime number.
  while not is_prime(_lowerCAmelCase     ):
   number += 1

    # precondition
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and ans[0] != p_number_a
     and ans[len(_lowerCAmelCase     ) - 1] != p_number_a
 ), "'ans' must been a list without the arguments"

 # 'ans' contains not 'pNumber1' and 'pNumber2' !
 return ans



def 		A_				(     _lowerCAmelCase     )						-> List[str]:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n >= 1), "'n' must been int and >= 1"

 UpperCamelCase	:					Dict       	=   []  # will be returned.

 for divisor in range(1							,   n + 1     ):
  if n % divisor == 0:
   ans.append(_lowerCAmelCase     )

    # precondition
 assert ans[0] == 1 and ans[len(_lowerCAmelCase     ) - 1] == n, "Error in function getDivisiors(...)"

 return ans



def 		A_				(     _lowerCAmelCase     )						-> int:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (
     number > 1
 ), "'number' must been an int and >= 1"

 UpperCamelCase	:					int       	=   get_divisors(_lowerCAmelCase     )

 # precondition
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (divisors[0] == 1)
     and (divisors[len(_lowerCAmelCase     ) - 1] == number)
 ), "Error in help-function getDivisiors(...)"

 # summed all divisors up to 'number' (exclusive), hence [:-1]
 return sum(divisors[:-1]     ) == number



def 		A_				(     _lowerCAmelCase							,   _lowerCAmelCase     )						-> Optional[Any]:
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (denominator != 0)
 ), "The arguments must been from type int and 'denominator' != 0"

 # build the greatest common divisor of numerator and denominator.
 UpperCamelCase	:					List[str]       	=   gcd(abs(_lowerCAmelCase     )							,   abs(_lowerCAmelCase     )     )

 # precondition
 assert (
     isinstance(_lowerCAmelCase							,   _lowerCAmelCase     )
     and (numerator % gcd_of_fraction == 0)
     and (denominator % gcd_of_fraction == 0)
 ), "Error in function gcd(...,...)"

 return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)



def 		A_				(     _lowerCAmelCase     )						-> Dict:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n >= 0), "'n' must been a int and >= 0"

 UpperCamelCase	:					str       	=   1  # this will be return.

 for factor in range(1							,   n + 1     ):
  ans *= factor

 return ans



def 		A_				(     _lowerCAmelCase     )						-> Tuple:
 assert isinstance(_lowerCAmelCase							,   _lowerCAmelCase     ) and (n >= 0), "'n' must been an int and >= 0"

 UpperCamelCase	:					Dict       	=   0
 UpperCamelCase	:					Dict       	=   1
 UpperCamelCase	:					Union[str, Any]       	=   1  # this will be return

 for _ in range(n - 1     ):
  UpperCamelCase	:					Any       	=   ans
  ans += fiba
  UpperCamelCase	:					str       	=   tmp

 return ans
