




'''simple docstring'''





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        __snake_case  (a__		):
				lowerCAmelCase__				=     42






class        __snake_case  (a__		):



				def __init__(      self      :		Optional[int]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		Any		,	_UpperCAmelCase      :		Union[str, Any]		,	_UpperCAmelCase      :		Union[str, Any]		,	)  ->    Optional[int]:





								'''simple docstring'''




								super().__init__()

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



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]		,	_UpperCAmelCase      :		Union[str, Any]		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		List[str]		,	_UpperCAmelCase      :		Optional[int]		,	_UpperCAmelCase      :		Optional[int]      )  ->    str:





								'''simple docstring'''




								if latents is None:
												_lowerCAmelCase    :    List[Any]										=      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    :    Optional[int]										=      latents.to(lowerCAmelCase__      )

								_lowerCAmelCase    :    Dict										=      latents * scheduler.init_noise_sigma
								return latents



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		List[str]=0      )  ->    List[str]:





								'''simple docstring'''




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

								_lowerCAmelCase    :    Tuple										=      torch.device(f"cuda:{gpu_id}"      )

								_lowerCAmelCase    :    Union[str, Any]										=      [self.image_encoder, self.prior]
								for cpu_offloaded_model in models:
												if cpu_offloaded_model is not None:
																cpu_offload(lowerCAmelCase__		,	lowerCAmelCase__      )



				@property
				def       SCREAMING_SNAKE_CASE       (      self      :		str      )  ->    int:





								'''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(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       SCREAMING_SNAKE_CASE       (      self      :		Any		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		Dict		,	)  ->    str:





								'''simple docstring'''




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

								if not isinstance(lowerCAmelCase__		,	torch.Tensor      ):
												_lowerCAmelCase    :    Union[str, Any]										=      self.image_processor(lowerCAmelCase__		,	return_tensors="""pt"""      ).pixel_values[0].unsqueeze(0      )

								_lowerCAmelCase    :    List[Any]										=      image.to(dtype=self.image_encoder.dtype		,	device=lowerCAmelCase__      )

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

								_lowerCAmelCase    :    Any										=      image_embeds.repeat_interleave(lowerCAmelCase__		,	dim=0      )

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

								return image_embeds



				@torch.no_grad()
				@replace_example_docstring(lowerCAmelCase__      )
				def __call__(      self      :		Union[str, Any]		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		int = 1		,	_UpperCAmelCase      :		Optional[Any] = 25		,	_UpperCAmelCase      :		Any = None		,	_UpperCAmelCase      :		Optional[Any] = None		,	_UpperCAmelCase      :		Union[str, Any] = 4.0		,	_UpperCAmelCase      :		Any = 64		,	_UpperCAmelCase      :		Optional[int] = "pil"		,	_UpperCAmelCase      :		int = True		,	)  ->    List[Any]:





								'''simple docstring'''




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

								_lowerCAmelCase    :    Tuple										=      self._execution_device

								_lowerCAmelCase    :    Optional[Any]										=      batch_size * num_images_per_prompt

								_lowerCAmelCase    :    int										=      guidance_scale > 1.0
								_lowerCAmelCase    :    int										=      self._encode_image(lowerCAmelCase__		,	lowerCAmelCase__		,	lowerCAmelCase__		,	lowerCAmelCase__      )

								# prior

								self.scheduler.set_timesteps(lowerCAmelCase__		,	device=lowerCAmelCase__      )
								_lowerCAmelCase    :    Any										=      self.scheduler.timesteps

								_lowerCAmelCase    :    str										=      self.prior.config.num_embeddings
								_lowerCAmelCase    :    Tuple										=      self.prior.config.embedding_dim

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

												_lowerCAmelCase    :    str										=      self.prior(
												    lowerCAmelCase__		,	timestep=lowerCAmelCase__		,	proj_embedding=lowerCAmelCase__		,	).predicted_image_embedding

												# remove the variance
												_lowerCAmelCase    :    List[Any]										=      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    :    Optional[Any]										=      noise_pred.chunk(2      )
																_lowerCAmelCase    :    Optional[Any]										=      noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

												_lowerCAmelCase    :    List[str]										=      self.scheduler.step(
												    lowerCAmelCase__		,	timestep=lowerCAmelCase__		,	sample=lowerCAmelCase__		,	).prev_sample

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

								_lowerCAmelCase    :    Any										=      []
								for i, latent in enumerate(lowerCAmelCase__      ):
												print()
												_lowerCAmelCase    :    Dict										=      self.renderer.decode(
												    latent[None, :]		,	lowerCAmelCase__		,	size=lowerCAmelCase__		,	ray_batch_size=4096		,	n_coarse_samples=64		,	n_fine_samples=128		,	)

												images.append(lowerCAmelCase__      )

								_lowerCAmelCase    :    int										=      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    :    Any										=      images.cpu().numpy()

								if output_type == "pil":
												_lowerCAmelCase    :    Any										=      [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 sys

_lowerCamelCase      :  Optional[Any]      						=						(
    "73167176531330624919225119674426574742355349194934"
    "96983520312774506326239578318016984801869478851843"
    "85861560789112949495459501737958331952853208805511"
    "12540698747158523863050715693290963295227443043557"
    "66896648950445244523161731856403098711121722383113"
    "62229893423380308135336276614282806444486645238749"
    "30358907296290491560440772390713810515859307960866"
    "70172427121883998797908792274921901699720888093776"
    "65727333001053367881220235421809751254540594752243"
    "52584907711670556013604839586446706324415722155397"
    "53697817977846174064955149290862569321978468622482"
    "83972241375657056057490261407972968652414535100474"
    "82166370484403199890008895243450658541227588666881"
    "16427171479924442928230863465674813919123162824586"
    "17866458359124566529476545682848912883142607690042"
    "24219022671055626321111109370544217506941658960408"
    "07198403850962455444362981230987879927244284909188"
    "84580156166097919133875499200524063689912560717606"
    "05886116467109405077541002256983155200055935729725"
    "71636269561882670428252483600823257530420752963450"
)




def 							_UpperCAmelCase  (UpperCamelCase_ : str = N       ):
				'''simple docstring'''
				_lowerCAmelCase    :    List[str]										=      -sys.maxsize - 1
				for i in range(len(UpperCamelCase_       ) - 12       ):
								_lowerCAmelCase    :    List[str]										=      1
								for j in range(13       ):
												product *= int(n[i + j]       )
								if product > largest_product:
												_lowerCAmelCase    :    Any										=      product
				return largest_product


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

