




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


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

_lowerCamelCase					:     Union[str, Any]					  =  "\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 				__snake_case     (_a						):
				lowerCAmelCase__			=   42






class 				__snake_case     (_a						):



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





								'''simple docstring'''




								super().__init__()

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



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





								'''simple docstring'''




								if latents is None:
												_lowerCAmelCase			:			str        =					randn_tensor(_UpperCAmelCase						,		generator=_UpperCAmelCase						,		device=_UpperCAmelCase						,		dtype=_UpperCAmelCase					)
								else:
												if latents.shape != shape:
																raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"					)
												_lowerCAmelCase			:			List[Any]        =					latents.to(_UpperCAmelCase					)

								_lowerCAmelCase			:			List[str]        =					latents * scheduler.init_noise_sigma
								return latents



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





								'''simple docstring'''




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

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

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



				def 					SCREAMING_SNAKE_CASE				(					self					:						str						,		_UpperCAmelCase					:						Dict=0					)     ->			Union[str, 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."""					)

								_lowerCAmelCase			:			List[str]        =					torch.device(f"cuda:{gpu_id}"					)

								if self.device.type != "cpu":
												self.to("""cpu"""						,		silence_dtype_warnings=_UpperCAmelCase					)
												torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

								_lowerCAmelCase			:			Union[str, Any]        =					None
								for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
												_lowerCAmelCase    ,			_lowerCAmelCase			:			Tuple        =					cpu_offload_with_hook(_UpperCAmelCase						,		_UpperCAmelCase						,		prev_module_hook=_UpperCAmelCase					)

								if self.safety_checker is not None:
												_lowerCAmelCase    ,			_lowerCAmelCase			:			Optional[int]        =					cpu_offload_with_hook(self.safety_checker						,		_UpperCAmelCase						,		prev_module_hook=_UpperCAmelCase					)

								# We'll offload the last model manually.
								_lowerCAmelCase			:			List[Any]        =					hook



				@property
				def 					SCREAMING_SNAKE_CASE				(					self					:						Union[str, Any]					)     ->			Dict:





								'''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(_UpperCAmelCase						,		"""_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					:						int						,		_UpperCAmelCase					:						Optional[int]						,		_UpperCAmelCase					:						Union[str, Any]						,		_UpperCAmelCase					:						Union[str, Any]						,		_UpperCAmelCase					:						Union[str, Any]						,		)     ->			Optional[Any]:





								'''simple docstring'''




								len(_UpperCAmelCase					) if isinstance(_UpperCAmelCase						,		_UpperCAmelCase					) else 1

								# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
								_lowerCAmelCase			:			Tuple        =					0
								# get prompt text embeddings
								_lowerCAmelCase			:			Tuple        =					self.tokenizer(
								    _UpperCAmelCase						,		padding="""max_length"""						,		max_length=self.tokenizer.model_max_length						,		truncation=_UpperCAmelCase						,		return_tensors="""pt"""						,		)
								_lowerCAmelCase			:			List[str]        =					text_inputs.input_ids
								_lowerCAmelCase			:			int        =					self.tokenizer(_UpperCAmelCase						,		padding="""longest"""						,		return_tensors="""pt"""					).input_ids

								if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_UpperCAmelCase						,		_UpperCAmelCase					):
												_lowerCAmelCase			:			Any        =					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			:			Optional[int]        =					self.text_encoder(text_input_ids.to(_UpperCAmelCase					)					)
								_lowerCAmelCase			:			Optional[Any]        =					text_encoder_output.text_embeds

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

								if do_classifier_free_guidance:
												_lowerCAmelCase			:			Optional[Any]        =					torch.zeros_like(_UpperCAmelCase					)

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

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

								return prompt_embeds



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





								'''simple docstring'''




								if isinstance(_UpperCAmelCase						,		_UpperCAmelCase					):
												_lowerCAmelCase			:			Any        =					1
								elif isinstance(_UpperCAmelCase						,		_UpperCAmelCase					):
												_lowerCAmelCase			:			List[Any]        =					len(_UpperCAmelCase					)
								else:
												raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_UpperCAmelCase					)}"					)

								_lowerCAmelCase			:			int        =					self._execution_device

								_lowerCAmelCase			:			int        =					batch_size * num_images_per_prompt

								_lowerCAmelCase			:			List[str]        =					guidance_scale > 1.0
								_lowerCAmelCase			:			Union[str, Any]        =					self._encode_prompt(_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase					)

								# prior

								self.scheduler.set_timesteps(_UpperCAmelCase						,		device=_UpperCAmelCase					)
								_lowerCAmelCase			:			List[Any]        =					self.scheduler.timesteps

								_lowerCAmelCase			:			Union[str, Any]        =					self.prior.config.num_embeddings
								_lowerCAmelCase			:			int        =					self.prior.config.embedding_dim

								_lowerCAmelCase			:			Tuple        =					self.prepare_latents(
								    (batch_size, num_embeddings * embedding_dim)						,		prompt_embeds.dtype						,		_UpperCAmelCase						,		_UpperCAmelCase						,		_UpperCAmelCase						,		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			:			Optional[int]        =					latents.reshape(latents.shape[0]						,		_UpperCAmelCase						,		_UpperCAmelCase					)

								for i, t in enumerate(self.progress_bar(_UpperCAmelCase					)					):
												# expand the latents if we are doing classifier free guidance
												_lowerCAmelCase			:			List[Any]        =					torch.cat([latents] * 2					) if do_classifier_free_guidance else latents
												_lowerCAmelCase			:			Optional[Any]        =					self.scheduler.scale_model_input(_UpperCAmelCase						,		_UpperCAmelCase					)

												_lowerCAmelCase			:			Optional[Any]        =					self.prior(
												    _UpperCAmelCase						,		timestep=_UpperCAmelCase						,		proj_embedding=_UpperCAmelCase						,		).predicted_image_embedding

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

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

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

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

								_lowerCAmelCase			:			Union[str, Any]        =					torch.stack(_UpperCAmelCase					)

								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			:			Union[str, Any]        =					images.cpu().numpy()

								if output_type == "pil":
												_lowerCAmelCase			:			Union[str, Any]        =					[self.numpy_to_pil(_UpperCAmelCase					) 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=_UpperCAmelCase					)








from __future__ import annotations

from collections import deque
from queue import Queue
from timeit import timeit

_lowerCamelCase       =	{
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E'],
}






def  SCREAMING_SNAKE_CASE__							(				UpperCamelCase__:							dict    ,      UpperCamelCase__:							str			):
		SCREAMING_SNAKE_CASE__								=					{start}
		SCREAMING_SNAKE_CASE__								=					[start]
		SCREAMING_SNAKE_CASE__								=					Queue()
		queue.put(UpperCamelCase__			)
		while not queue.empty():
				SCREAMING_SNAKE_CASE__								=					queue.get()
				for w in graph[v]:
						if w not in explored:
								explored.add(UpperCamelCase__			)
								result.append(UpperCamelCase__			)
								queue.put(UpperCamelCase__			)
		return result






def  SCREAMING_SNAKE_CASE__							(				UpperCamelCase__:							dict    ,      UpperCamelCase__:							str			):
		SCREAMING_SNAKE_CASE__								=					{start}
		SCREAMING_SNAKE_CASE__								=					[start]
		SCREAMING_SNAKE_CASE__								=					deque([start]			)
		while queue:
				SCREAMING_SNAKE_CASE__								=					queue.popleft()
				for child in graph[v]:
						if child not in visited:
								visited.add(UpperCamelCase__			)
								result.append(UpperCamelCase__			)
								queue.append(UpperCamelCase__			)
		return result






def  SCREAMING_SNAKE_CASE__							(				UpperCamelCase__:							str			):
		SCREAMING_SNAKE_CASE__								=					f'''from __main__ import G, {name}'''
		SCREAMING_SNAKE_CASE__								=					10_000
		SCREAMING_SNAKE_CASE__								=					timeit(f'''{name}(G, \'A\')'''    ,      setup=UpperCamelCase__    ,      number=UpperCamelCase__			)
		print(f'''{name:<35} finished {number} runs in {res:.5f} seconds'''			)


if __name__ == "__main__":
	import doctest

	doctest.testmod()

	benchmark_function('breadth_first_search')
	benchmark_function('breadth_first_search_with_deque')
	# breadth_first_search                finished 10000 runs in 0.20999 seconds
	# breadth_first_search_with_deque     finished 10000 runs in 0.01421 seconds