


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


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

A      = "\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n"


@dataclass
class     lowercase__  (					__SCREAMING_SNAKE_CASE		):
  A__=  42




class     lowercase__  (					__SCREAMING_SNAKE_CASE		):






  def __init__(					self      :					str		,						_lowercase      :					PriorTransformer		,						_lowercase      :					CLIPVisionModel		,						_lowercase      :					CLIPImageProcessor		,						_lowercase      :					HeunDiscreteScheduler		,						_lowercase      :					ShapERenderer		,						):




         """simple docstring"""







         super().__init__()

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






  def 			_UpperCAmelCase  (					self      :					int		,						_lowercase      :					Any		,						_lowercase      :					Union[str, Any]		,						_lowercase      :					Tuple		,						_lowercase      :					Tuple		,						_lowercase      :					List[str]		,						_lowercase      :					Optional[int] ):




         """simple docstring"""







         if latents is None:
                UpperCAmelCase__										=     randn_tensor(_lowercase		,						generator=_lowercase		,						device=_lowercase		,						dtype=_lowercase )
         else:
                if latents.shape != shape:
                       raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" )
                UpperCAmelCase__										=     latents.to(_lowercase )

         UpperCAmelCase__										=     latents * scheduler.init_noise_sigma
         return latents






  def 			_UpperCAmelCase  (					self      :					List[Any]		,						_lowercase      :					Any=0 ):




         """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.image_encoder, self.prior]
         for cpu_offloaded_model in models:
                if cpu_offloaded_model is not None:
                       cpu_offload(_lowercase		,						_lowercase )






  @property
  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """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(_lowercase		,						"_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      :					List[Any]		,						_lowercase      :					Optional[int]		,						_lowercase      :					Tuple		,						_lowercase      :					List[str]		,						_lowercase      :					Dict		,						):




         """simple docstring"""







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

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

         UpperCAmelCase__										=     image.to(dtype=self.image_encoder.dtype		,						device=_lowercase )

         UpperCAmelCase__										=     self.image_encoder(_lowercase )["last_hidden_state"]
         UpperCAmelCase__										=     image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

         UpperCAmelCase__										=     image_embeds.repeat_interleave(_lowercase		,						dim=0 )

         if do_classifier_free_guidance:
                UpperCAmelCase__										=     torch.zeros_like(_lowercase )

                # 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_image_embeds, image_embeds] )

         return image_embeds






  @torch.no_grad()
  @replace_example_docstring(_lowercase )
  def __call__(					self      :					List[str]		,						_lowercase      :					Union[PIL.Image.Image, List[PIL.Image.Image]]		,						_lowercase      :					int = 1		,						_lowercase      :					int = 25		,						_lowercase      :					Optional[Union[torch.Generator, List[torch.Generator]]] = None		,						_lowercase      :					Optional[torch.FloatTensor] = None		,						_lowercase      :					float = 4.0		,						_lowercase      :					int = 64		,						_lowercase      :					Optional[str] = "pil"		,						_lowercase      :					bool = True		,						):




         """simple docstring"""







         if isinstance(_lowercase		,						PIL.Image.Image ):
                UpperCAmelCase__										=     1
         elif isinstance(_lowercase		,						torch.Tensor ):
                UpperCAmelCase__										=     image.shape[0]
         elif isinstance(_lowercase		,						_lowercase ) and isinstance(image[0]		,						(torch.Tensor, PIL.Image.Image) ):
                UpperCAmelCase__										=     len(_lowercase )
         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(_lowercase )}""" )

         UpperCAmelCase__										=     self._execution_device

         UpperCAmelCase__										=     batch_size * num_images_per_prompt

         UpperCAmelCase__										=     guidance_scale > 1.0
         UpperCAmelCase__										=     self._encode_image(_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )

         # prior

         self.scheduler.set_timesteps(_lowercase		,						device=_lowercase )
         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)		,						image_embeds.dtype		,						_lowercase		,						_lowercase		,						_lowercase		,						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]		,						_lowercase		,						_lowercase )

         for i, t in enumerate(self.progress_bar(_lowercase ) ):
                # 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(_lowercase		,						_lowercase )

                UpperCAmelCase__										=     self.prior(
                    _lowercase		,						timestep=_lowercase		,						proj_embedding=_lowercase		,						).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(
                    _lowercase		,						timestep=_lowercase		,						sample=_lowercase		,						).prev_sample

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

         UpperCAmelCase__										=     []
         for i, latent in enumerate(_lowercase ):
                print()
                UpperCAmelCase__										=     self.renderer.decode(
                    latent[None, :]		,						_lowercase		,						size=_lowercase		,						ray_batch_size=40_96		,						n_coarse_samples=64		,						n_fine_samples=1_28		,						)

                images.append(_lowercase )

         UpperCAmelCase__										=     torch.stack(_lowercase )

         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(_lowercase ) 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=_lowercase )









from __future__ import annotations





def __UpperCAmelCase       (		__A			)						->					list[int]:



       '''simple docstring'''





       UpperCAmelCase__										=     [True] * limit
       UpperCAmelCase__										=     False
       UpperCAmelCase__										=     False
       UpperCAmelCase__										=     True

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

       UpperCAmelCase__										=     [2]

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

       return primes





def __UpperCAmelCase       (		__A = 1_0_0_0_0_0_0			)						->					int:



       '''simple docstring'''





       UpperCAmelCase__										=     prime_sieve(__A			)
       UpperCAmelCase__										=     0
       UpperCAmelCase__										=     0

       for i in range(len(__A			)			):
              for j in range(i + length ,						len(__A			)			):
                     UpperCAmelCase__										=     sum(primes[i:j]			)
                     if sol >= ceiling:
                            break

                     if sol in primes:
                            UpperCAmelCase__										=     j - i
                            UpperCAmelCase__										=     sol

       return largest


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





