


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


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

__UpperCamelCase      						=    '\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     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






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







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			def __init__(							self ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  ):

						'''simple docstring'''


						super().__init__()

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




			def 			snake_case__			(							self ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  snake_case       ):

						'''simple docstring'''


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

						UpperCamelCase__   =    latents * scheduler.init_noise_sigma
						return latents




			def 			snake_case__			(							self ,  snake_case=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.text_encoder, self.prior]
						for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
												cpu_offload(snake_case ,  snake_case       )




			def 			snake_case__			(							self ,  snake_case=0       ):

						'''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=snake_case       )
									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(snake_case ,  snake_case ,  prev_module_hook=snake_case       )

						if self.safety_checker is not None:
									UpperCamelCase__, UpperCamelCase__   =    cpu_offload_with_hook(self.safety_checker ,  snake_case ,  prev_module_hook=snake_case       )

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




			@property
			def 			snake_case__			(							self       ):

						'''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(snake_case ,  "_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 			snake_case__			(							self ,  snake_case ,  snake_case ,  snake_case ,  snake_case ,  ):

						'''simple docstring'''


						len(snake_case       ) if isinstance(snake_case ,  snake_case       ) 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(
						    snake_case ,  padding="max_length" ,  max_length=self.tokenizer.model_max_length ,  truncation=snake_case ,  return_tensors="pt" ,  )
						UpperCamelCase__   =    text_inputs.input_ids
						UpperCamelCase__   =    self.tokenizer(snake_case ,  padding="longest" ,  return_tensors="pt"       ).input_ids

						if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(snake_case ,  snake_case       ):
									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(snake_case       )       )
						UpperCamelCase__   =    text_encoder_output.text_embeds

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

						if do_classifier_free_guidance:
									UpperCamelCase__   =    torch.zeros_like(snake_case       )

									# 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(snake_case       )
			def __call__(							self ,  snake_case ,  snake_case = 1 ,  snake_case = 25 ,  snake_case = None ,  snake_case = None ,  snake_case = 4.0 ,  snake_case = 64 ,  snake_case = "pil" ,  snake_case = True ,  ):

						'''simple docstring'''


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

						UpperCamelCase__   =    self._execution_device

						UpperCamelCase__   =    batch_size * num_images_per_prompt

						UpperCamelCase__   =    guidance_scale > 1.0
						UpperCamelCase__   =    self._encode_prompt(snake_case ,  snake_case ,  snake_case ,  snake_case       )

						# prior

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

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

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

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

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

						UpperCamelCase__   =    torch.stack(snake_case       )

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






from typing import Optional

from ..utils.logging import get_logger
from .audio_classificiation import AudioClassification
from .automatic_speech_recognition import AutomaticSpeechRecognition
from .base import TaskTemplate
from .image_classification import ImageClassification
from .language_modeling import LanguageModeling
from .question_answering import QuestionAnsweringExtractive
from .summarization import Summarization
from .text_classification import TextClassification


__UpperCamelCase      						=    [
    'AutomaticSpeechRecognition',
    'AudioClassification',
    'ImageClassification',
    'LanguageModeling',
    'QuestionAnsweringExtractive',
    'Summarization',
    'TaskTemplate',
    'TextClassification',
]

__UpperCamelCase      						=    get_logger(__name__)


__UpperCamelCase      						=    {
    AutomaticSpeechRecognition.task: AutomaticSpeechRecognition,
    AudioClassification.task: AudioClassification,
    ImageClassification.task: ImageClassification,
    LanguageModeling.task: LanguageModeling,
    QuestionAnsweringExtractive.task: QuestionAnsweringExtractive,
    Summarization.task: Summarization,
    TextClassification.task: TextClassification,
}
def     UpperCamelCase_(			_A				:dict					)->						Optional[TaskTemplate]:
			UpperCamelCase__   =    task_template_dict.get("task"					)
			if task_name is None:
						logger.warning(F'''Couldn\'t find template for task \'{task_name}\'. Available templates: {list(_A					)}'''					)
						return None
			UpperCamelCase__   =    NAMEaTEMPLATE.get(_A					)
			return template.from_dict(_A					)


