




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


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

snake_case__ :						Optional[Any]     =			'''
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

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

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

        >>> guidance_scale = 15.0
        >>> prompt = "a shark"

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

        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")
        ```
'''





@dataclass
class     snake_case  (	_snake_case							):


   '''simple docstring'''







   UpperCamelCase__	:       Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]





class     snake_case  (	_snake_case							):


   '''simple docstring'''







   def __init__(					self     :	List[str]						,    lowerCamelCase_     :	PriorTransformer						,    lowerCamelCase_     :	CLIPTextModelWithProjection						,    lowerCamelCase_     :	CLIPTokenizer						,    lowerCamelCase_     :	HeunDiscreteScheduler						,    lowerCamelCase_     :	ShapERenderer						,    )					->Optional[Any]:
     '''simple docstring'''







     super().__init__()

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




   def 	UpperCAmelCase       (					self     :	List[Any]						,    lowerCamelCase_     :	Any						,    lowerCamelCase_     :	Optional[Any]						,    lowerCamelCase_     :	Dict						,    lowerCamelCase_     :	Dict						,    lowerCamelCase_     :	int						,    lowerCamelCase_     :	Any			)					->List[Any]:
     '''simple docstring'''







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

     UpperCAmelCase__    						=   latents * scheduler.init_noise_sigma
     return latents




   def 	UpperCAmelCase       (					self     :	Dict						,    lowerCamelCase_     :	Union[str, Any]=0			)					->Union[str, Any]:
     '''simple docstring'''







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

     UpperCAmelCase__    						=   torch.device(f'''cuda:{gpu_id}'''			)

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




   def 	UpperCAmelCase       (					self     :	List[Any]						,    lowerCamelCase_     :	Union[str, Any]=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."""			)

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

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

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

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




   @property
   def 	UpperCAmelCase       (					self     :	List[Any]			)					->int:
     '''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(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 	UpperCAmelCase       (					self     :	Any						,    lowerCamelCase_     :	Dict						,    lowerCamelCase_     :	Tuple						,    lowerCamelCase_     :	Optional[Any]						,    lowerCamelCase_     :	Optional[Any]						,    )					->Any:
     '''simple docstring'''







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

     UpperCAmelCase__    						=   self.text_encoder(text_input_ids.to(lowerCamelCase_			)			)
     UpperCAmelCase__    						=   text_encoder_output.text_embeds

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

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

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

     return prompt_embeds







   @torch.no_grad()
   @replace_example_docstring(lowerCamelCase_			)
   def __call__(					self     :	Any						,    lowerCamelCase_     :	str						,    lowerCamelCase_     :	int = 1						,    lowerCamelCase_     :	int = 25						,    lowerCamelCase_     :	Optional[Union[torch.Generator, List[torch.Generator]]] = None						,    lowerCamelCase_     :	Optional[torch.FloatTensor] = None						,    lowerCamelCase_     :	float = 4.0						,    lowerCamelCase_     :	int = 64						,    lowerCamelCase_     :	Optional[str] = "pil"						,    lowerCamelCase_     :	bool = True						,    )					->Optional[int]:
     '''simple docstring'''







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

     UpperCAmelCase__    						=   self._execution_device

     UpperCAmelCase__    						=   batch_size * num_images_per_prompt

     UpperCAmelCase__    						=   guidance_scale > 1.0
     UpperCAmelCase__    						=   self._encode_prompt(lowerCamelCase_						,    lowerCamelCase_						,    lowerCamelCase_						,    lowerCamelCase_			)

     # prior

     self.scheduler.set_timesteps(lowerCamelCase_						,    device=lowerCamelCase_			)
     UpperCAmelCase__    						=   self.scheduler.timesteps

     UpperCAmelCase__    						=   self.prior.config.num_embeddings
     UpperCAmelCase__    						=   self.prior.config.embedding_dim

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

       UpperCAmelCase__    						=   self.prior(
           lowerCamelCase_						,    timestep=lowerCamelCase_						,    proj_embedding=lowerCamelCase_						,    ).predicted_image_embedding

       # remove the variance
       UpperCAmelCase__						,					UpperCAmelCase__    						=   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__    						=   noise_pred.chunk(2			)
         UpperCAmelCase__    						=   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

       UpperCAmelCase__    						=   self.scheduler.step(
           lowerCamelCase_						,    timestep=lowerCamelCase_						,    sample=lowerCamelCase_						,    ).prev_sample

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

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

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

     UpperCAmelCase__    						=   images.cpu().numpy()

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










from __future__ import annotations

from collections import Counter


def 						lowercase		(     _lowerCAmelCase      ):
  UpperCAmelCase__    						=   [True] * n
  UpperCAmelCase__    						=   False
  UpperCAmelCase__    						=   False
  UpperCAmelCase__    						=   True

  for i in range(3   ,     int(n**0.5 + 1      )   ,     2      ):
    UpperCAmelCase__    						=   i * 2
    while index < n:
      UpperCAmelCase__    						=   False
      UpperCAmelCase__    						=   index + i

  UpperCAmelCase__    						=   [2]

  for i in range(3   ,     _lowerCAmelCase   ,     2      ):
    if is_prime[i]:
      primes.append(_lowerCAmelCase      )

  return primes


def 						lowercase		(     _lowerCAmelCase      ):
  UpperCAmelCase__    						=   str(_lowerCAmelCase      )
  UpperCAmelCase__    						=   []
  UpperCAmelCase__    						=   ["""0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9"""]

  for duplicate in Counter(_lowerCAmelCase      ) - Counter(set(_lowerCAmelCase      )      ):
    UpperCAmelCase__    						=   [int(number_str.replace(_lowerCAmelCase   ,     _lowerCAmelCase      )      ) for digit in digits]
    replacements.append(_lowerCAmelCase      )

  return replacements


def 						lowercase		(     _lowerCAmelCase = 8      ):
  UpperCAmelCase__    						=   set()

  # Filter primes with less than 3 replaceable digits
  UpperCAmelCase__    						=   {
      x for x in set(prime_sieve(100_0000      )      ) if len(str(_lowerCAmelCase      )      ) - len(set(str(_lowerCAmelCase      )      )      ) >= 3
  }

  for prime in primes:
    if prime in numbers_checked:
      continue

    UpperCAmelCase__    						=   digit_replacements(_lowerCAmelCase      )

    for family in replacements:
      numbers_checked.update(_lowerCAmelCase      )
      UpperCAmelCase__    						=   primes.intersection(_lowerCAmelCase      )

      if len(_lowerCAmelCase      ) != family_length:
        continue

      return min(_lowerCAmelCase      )

  return -1


if __name__ == "__main__":
   print(solution())




