


'''simple docstring'''




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


__lowercase	:   List[Any]   		=					logging.get_logger(__name__)  # pylint: disable=invalid-name

__lowercase	:   Optional[int]   		=					"""
    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 (			a__ ):
							"""simple docstring"""





							__a				       =  42





class _snake_case (			a__ ):
							"""simple docstring"""





							def __init__( self      ,					__A      ,					__A      ,					__A      ,					__A      ,					__A      ,					)  ->List[Any]:



											"""simple docstring"""







											super().__init__()

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







							def 		__SCREAMING_SNAKE_CASE( self      ,					__A      ,					__A      ,					__A      ,					__A      ,					__A      ,					__A						)  ->List[str]:



											"""simple docstring"""







											if latents is None:
															__lowerCamelCase		:   Any           =       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}'						)
															__lowerCamelCase		:   int           =       latents.to(__A						)

											__lowerCamelCase		:   int           =       latents * scheduler.init_noise_sigma
											return latents







							def 		__SCREAMING_SNAKE_CASE( self      ,					__A=0						)  ->Any:



											"""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		:   Any           =       [self.text_encoder, self.prior]
											for cpu_offloaded_model in models:
															if cpu_offloaded_model is not None:
																			cpu_offload(__A      ,					__A						)







							def 		__SCREAMING_SNAKE_CASE( self      ,					__A=0						)  ->Optional[int]:



											"""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		:   Dict           =       torch.device(f'cuda:{gpu_id}'						)

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

											__lowerCamelCase		:   List[str]           =       None
											for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
															__lowerCamelCase    ,       __lowerCamelCase		:   Any           =       cpu_offload_with_hook(__A      ,					__A      ,					prev_module_hook=__A						)

											if self.safety_checker is not None:
															__lowerCamelCase    ,       __lowerCamelCase		:   Optional[Any]           =       cpu_offload_with_hook(self.safety_checker      ,					__A      ,					prev_module_hook=__A						)

											# We'll offload the last model manually.
											__lowerCamelCase		:   Dict           =       hook







							@property
							def 		__SCREAMING_SNAKE_CASE( self						)  ->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(__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 		__SCREAMING_SNAKE_CASE( self      ,					__A      ,					__A      ,					__A      ,					__A      ,					)  ->Optional[int]:



											"""simple docstring"""







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

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

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

											__lowerCamelCase		:   Any           =       prompt_embeds.repeat_interleave(__A      ,					dim=0						)
											# in Shap-E it normalize the prompt_embeds and then later rescale it
											__lowerCamelCase		:   Tuple           =       prompt_embeds / torch.linalg.norm(__A      ,					dim=-1      ,					keepdim=__A						)

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

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

											return prompt_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      ,					)  ->List[Any]:



											"""simple docstring"""







											if isinstance(__A      ,					__A						):
															__lowerCamelCase		:   List[str]           =       1
											elif isinstance(__A      ,					__A						):
															__lowerCamelCase		:   Dict           =       len(__A						)
											else:
															raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__A						)}'						)

											__lowerCamelCase		:   int           =       self._execution_device

											__lowerCamelCase		:   Union[str, Any]           =       batch_size * num_images_per_prompt

											__lowerCamelCase		:   Union[str, Any]           =       guidance_scale > 1.0
											__lowerCamelCase		:   str           =       self._encode_prompt(__A      ,					__A      ,					__A      ,					__A						)

											# prior

											self.scheduler.set_timesteps(__A      ,					device=__A						)
											__lowerCamelCase		:   Dict           =       self.scheduler.timesteps

											__lowerCamelCase		:   Tuple           =       self.prior.config.num_embeddings
											__lowerCamelCase		:   Any           =       self.prior.config.embedding_dim

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

															__lowerCamelCase		:   List[Any]           =       self.prior(
															    __A      ,					timestep=__A      ,					proj_embedding=__A      ,					).predicted_image_embedding

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

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

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

											__lowerCamelCase		:   List[str]           =       []
											for i, latent in enumerate(__A						):
															__lowerCamelCase		:   Optional[int]           =       self.renderer.decode(
															    latent[None, :]      ,					__A      ,					size=__A      ,					ray_batch_size=4096      ,					n_coarse_samples=64      ,					n_fine_samples=128      ,					)
															images.append(__A						)

											__lowerCamelCase		:   Dict           =       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}'						)

											__lowerCamelCase		:   int           =       images.cpu().numpy()

											if output_type == "pil":
															__lowerCamelCase		:   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						)









'''simple docstring'''




from collections import deque





def 				a_							(    lowercase     )      ->Tuple:






				'''simple docstring'''

				return input(lowercase     ).strip().split(" "     )





def 				a_							(    lowercase				,    lowercase     )      ->dict[int, list[int]]:






				'''simple docstring'''

				__lowerCamelCase		:   dict[int, list[int]]           =       {}
				for i in range(lowercase     ):
								__lowerCamelCase		:   int           =       []

				for e in range(lowercase     ):
								__lowerCamelCase    ,       __lowerCamelCase		:   int           =       (int(lowercase     ) for i in _input(F'Edge {e + 1}: <node1> <node2> '     ))
								graph[x].append(lowercase     )
				return graph





def 				a_							(    lowercase				,    lowercase     )      ->dict[int, list[int]]:






				'''simple docstring'''

				__lowerCamelCase		:   dict[int, list[int]]           =       {}
				for i in range(lowercase     ):
								__lowerCamelCase		:   Any           =       []

				for e in range(lowercase     ):
								__lowerCamelCase    ,       __lowerCamelCase		:   Dict           =       (int(lowercase     ) for i in _input(F'Edge {e + 1}: <node1> <node2> '     ))
								graph[x].append(lowercase     )
								graph[y].append(lowercase     )
				return graph





def 				a_							(    lowercase				,    lowercase     )      ->dict[int, list[tuple[int, int]]]:






				'''simple docstring'''

				__lowerCamelCase		:   dict[int, list[tuple[int, int]]]           =       {}
				for i in range(lowercase     ):
								__lowerCamelCase		:   List[Any]           =       []

				for e in range(lowercase     ):
								__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase		:   int           =       (int(lowercase     ) for i in _input(F'Edge {e + 1}: <node1> <node2> <weight> '     ))
								graph[x].append((y, w)     )
								graph[y].append((x, w)     )
				return graph


if __name__ == "__main__":
				__lowercase		,		__lowercase	:   List[Any]   		=					(int(i) for i in _input("""Number of nodes and edges: """))

				__lowercase	:   Any   		=					int(
				    _input(
				        """Press 1 or 2 or 3 \n"""
				        """1. Unweighted directed \n"""
				        """2. Unweighted undirected \n"""
				        """3. Weighted undirected \n"""
				    )[0]
				)

				__lowercase	:   Any   		=					{
				    1: initialize_unweighted_directed_graph,
				    2: initialize_unweighted_undirected_graph,
				    3: initialize_weighted_undirected_graph,
				}[graph_choice](n, m)





def 				a_							(    lowercase				,    lowercase     )      ->Tuple:






				'''simple docstring'''

				__lowerCamelCase    ,       __lowerCamelCase		:   Dict           =       {s}, [s]
				print(lowercase     )
				while _s:
								__lowerCamelCase		:   int           =       0
								for i in g[_s[-1]]:
												if i not in vis:
																_s.append(lowercase     )
																vis.add(lowercase     )
																__lowerCamelCase		:   Tuple           =       1
																print(lowercase     )
																break
								if not flag:
												_s.pop()





def 				a_							(    lowercase				,    lowercase     )      ->List[str]:






				'''simple docstring'''

				__lowerCamelCase    ,       __lowerCamelCase		:   Tuple           =       {s}, deque([s]     )
				print(lowercase     )
				while q:
								__lowerCamelCase		:   Optional[Any]           =       q.popleft()
								for v in g[u]:
												if v not in vis:
																vis.add(lowercase     )
																q.append(lowercase     )
																print(lowercase     )





def 				a_							(    lowercase				,    lowercase     )      ->Any:






				'''simple docstring'''

				__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase		:   Optional[int]           =       {s: 0}, set(), {s: 0}
				while True:
								if len(lowercase     ) == len(lowercase     ) - 1:
												break
								__lowerCamelCase		:   str           =       10_0000
								for i in dist:
												if i not in known and dist[i] < mini:
																__lowerCamelCase		:   Any           =       dist[i]
																__lowerCamelCase		:   List[str]           =       i
								known.add(lowercase     )
								for v in g[u]:
												if v[0] not in known and dist[u] + v[1] < dist.get(v[0]				,    10_0000     ):
																__lowerCamelCase		:   Optional[int]           =       dist[u] + v[1]
																__lowerCamelCase		:   List[str]           =       u
				for i in dist:
								if i != s:
												print(dist[i]     )





def 				a_							(    lowercase				,    lowercase=None				,    lowercase=None     )      ->Optional[Any]:






				'''simple docstring'''

				if q is None:
								__lowerCamelCase		:   int           =       [1]
				if ind is None:
								__lowerCamelCase		:   Any           =       [0] * (len(lowercase     ) + 1)  # SInce oth Index is ignored
								for u in g:
												for v in g[u]:
																ind[v] += 1
								__lowerCamelCase		:   Tuple           =       deque()
								for i in g:
												if ind[i] == 0:
																q.append(lowercase     )
				if len(lowercase     ) == 0:
								return
				__lowerCamelCase		:   Optional[Any]           =       q.popleft()
				print(lowercase     )
				for w in g[v]:
								ind[w] -= 1
								if ind[w] == 0:
												q.append(lowercase     )
				topo(lowercase				,    lowercase				,    lowercase     )





def 				a_							(    )      ->Union[str, Any]:






				'''simple docstring'''

				__lowerCamelCase		:   Tuple           =       input().strip()
				__lowerCamelCase		:   Any           =       []
				for _ in range(lowercase     ):
								a.append(map(lowercase				,    input().strip().split()     )     )
				return a, n





def 				a_							(    lowercase     )      ->List[str]:






				'''simple docstring'''

				((__lowerCamelCase)    ,       (__lowerCamelCase))		:   Optional[int]           =       a_and_n
				__lowerCamelCase		:   Optional[int]           =       list(lowercase     )
				__lowerCamelCase		:   str           =       [[0] * n for i in range(lowercase     )]
				for k in range(lowercase     ):
								for i in range(lowercase     ):
												for j in range(lowercase     ):
																if dist[i][j] > dist[i][k] + dist[k][j]:
																				__lowerCamelCase		:   str           =       dist[i][k] + dist[k][j]
																				__lowerCamelCase		:   Tuple           =       k
				print(lowercase     )





def 				a_							(    lowercase				,    lowercase     )      ->Dict:






				'''simple docstring'''

				__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase		:   int           =       {s: 0}, set(), {s: 0}
				while True:
								if len(lowercase     ) == len(lowercase     ) - 1:
												break
								__lowerCamelCase		:   List[Any]           =       10_0000
								for i in dist:
												if i not in known and dist[i] < mini:
																__lowerCamelCase		:   str           =       dist[i]
																__lowerCamelCase		:   Optional[int]           =       i
								known.add(lowercase     )
								for v in g[u]:
												if v[0] not in known and v[1] < dist.get(v[0]				,    10_0000     ):
																__lowerCamelCase		:   Dict           =       v[1]
																__lowerCamelCase		:   List[str]           =       u
				return dist





def 				a_							(    )      ->Union[str, Any]:






				'''simple docstring'''

				__lowerCamelCase    ,       __lowerCamelCase		:   List[Any]           =       map(lowercase				,    input().split(" "     )     )
				__lowerCamelCase		:   Optional[Any]           =       []
				for _ in range(lowercase     ):
								edges.append(map(lowercase				,    input().split(" "     )     )     )
				return edges, n





def 				a_							(    lowercase     )      ->Optional[int]:






				'''simple docstring'''

				((__lowerCamelCase)    ,       (__lowerCamelCase))		:   Any           =       e_and_n
				e.sort(reverse=lowercase				,    key=lambda lowercase     : x[2]     )
				__lowerCamelCase		:   Optional[Any]           =       [{i} for i in range(1				,    n + 1     )]
				while True:
								if len(lowercase     ) == 1:
												break
								print(lowercase     )
								__lowerCamelCase		:   List[str]           =       e.pop()
								for i in range(len(lowercase     )     ):
												if x[0] in s[i]:
																break
								for j in range(len(lowercase     )     ):
												if x[1] in s[j]:
																if i == j:
																				break
																s[j].update(s[i]     )
																s.pop(lowercase     )
																break





def 				a_							(    lowercase     )      ->int:






				'''simple docstring'''

				__lowerCamelCase		:   Tuple           =       []
				for node in graph:
								if not graph[node]:
												isolated.append(lowercase     )
				return isolated





