
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     					=    logging.get_logger(__name__)  # pylint: disable=invalid-name

_lowerCamelCase     					=    '''
    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      SCREAMING_SNAKE_CASE__  (			UpperCAmelCase      ):





	'''simple docstring'''



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




class      SCREAMING_SNAKE_CASE__  (			UpperCAmelCase      ):





	'''simple docstring'''



	def __init__(						self			:					str    ,						lowercase			:					PriorTransformer    ,						lowercase			:					CLIPTextModelWithProjection    ,						lowercase			:					CLIPTokenizer    ,						lowercase			:					HeunDiscreteScheduler    ,						lowercase			:					ShapERenderer    ,						):


				'''simple docstring'''


				super().__init__()

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



	def 				A							(						self			:					Optional[int]    ,						lowercase			:					Tuple    ,						lowercase			:					Any    ,						lowercase			:					Optional[int]    ,						lowercase			:					str    ,						lowercase			:					Optional[int]    ,						lowercase			:					Tuple			):


				'''simple docstring'''


				if latents is None:
							_snake_case						=    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}'''			)
							_snake_case						=    latents.to(lowercase			)

				_snake_case						=    latents * scheduler.init_noise_sigma
				return latents



	def 				A							(						self			:					Union[str, Any]    ,						lowercase			:					Tuple=0			):


				'''simple docstring'''


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

				_snake_case						=    torch.device(f'''cuda:{gpu_id}'''			)

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



	def 				A							(						self			:					List[str]    ,						lowercase			:					Tuple=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.'			)

				_snake_case						=    torch.device(f'''cuda:{gpu_id}'''			)

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

				_snake_case						=    None
				for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
							_snake_case			,      _snake_case						=    cpu_offload_with_hook(lowercase    ,						lowercase    ,						prev_module_hook=lowercase			)

				if self.safety_checker is not None:
							_snake_case			,      _snake_case						=    cpu_offload_with_hook(self.safety_checker    ,						lowercase    ,						prev_module_hook=lowercase			)

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



	@property
	def 				A							(						self			:					Union[str, Any]			):


				'''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(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 				A							(						self			:					Any    ,						lowercase			:					Tuple    ,						lowercase			:					Optional[Any]    ,						lowercase			:					int    ,						lowercase			:					List[Any]    ,						):


				'''simple docstring'''


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

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

				if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowercase    ,						lowercase			):
							_snake_case						=    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}'''			)

				_snake_case						=    self.text_encoder(text_input_ids.to(lowercase			)			)
				_snake_case						=    text_encoder_output.text_embeds

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

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

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

				return prompt_embeds





	@torch.no_grad()
	@replace_example_docstring(lowercase			)
	def __call__(						self			:					List[str]    ,						lowercase			:					str    ,						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    ,						lowercase			):
							_snake_case						=    1
				elif isinstance(lowercase    ,						lowercase			):
							_snake_case						=    len(lowercase			)
				else:
							raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(lowercase			)}'''			)

				_snake_case						=    self._execution_device

				_snake_case						=    batch_size * num_images_per_prompt

				_snake_case						=    guidance_scale > 1.0
				_snake_case						=    self._encode_prompt(lowercase    ,						lowercase    ,						lowercase    ,						lowercase			)

				# prior

				self.scheduler.set_timesteps(lowercase    ,						device=lowercase			)
				_snake_case						=    self.scheduler.timesteps

				_snake_case						=    self.prior.config.num_embeddings
				_snake_case						=    self.prior.config.embedding_dim

				_snake_case						=    self.prepare_latents(
				    (batch_size, num_embeddings * embedding_dim)    ,						prompt_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
				_snake_case						=    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
							_snake_case						=    torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
							_snake_case						=    self.scheduler.scale_model_input(lowercase    ,						lowercase			)

							_snake_case						=    self.prior(
							    lowercase    ,						timestep=lowercase    ,						proj_embedding=lowercase    ,						).predicted_image_embedding

							# remove the variance
							_snake_case			,      _snake_case						=    noise_pred.split(
							    scaled_model_input.shape[2]    ,						dim=2			)  # batch_size, num_embeddings, embedding_dim

							if do_classifier_free_guidance is not None:
										_snake_case			,      _snake_case						=    noise_pred.chunk(2			)
										_snake_case						=    noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							_snake_case						=    self.scheduler.step(
							    lowercase    ,						timestep=lowercase    ,						sample=lowercase    ,						).prev_sample

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

				_snake_case						=    []
				for i, latent in enumerate(lowercase			):
							_snake_case						=    self.renderer.decode(
							    latent[None, :]    ,						lowercase    ,						size=lowercase    ,						ray_batch_size=4_096    ,						n_coarse_samples=64    ,						n_fine_samples=128    ,						)
							images.append(lowercase			)

				_snake_case						=    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}'''			)

				_snake_case						=    images.cpu().numpy()

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

# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
    is_vision_available,
)


_lowerCamelCase :       int     					=    {
    '''configuration_tvlt''': ['''TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TvltConfig'''],
    '''feature_extraction_tvlt''': ['''TvltFeatureExtractor'''],
    '''processing_tvlt''': ['''TvltProcessor'''],
}

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_lowerCamelCase :       str     					=    [
			    '''TVLT_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''TvltModel''',
			    '''TvltForPreTraining''',
			    '''TvltForAudioVisualClassification''',
			    '''TvltPreTrainedModel''',
			]

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_lowerCamelCase :       str     					=    ['''TvltImageProcessor''']


if TYPE_CHECKING:
			from .configuration_tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig
			from .processing_tvlt import TvltProcessor
			from .feature_extraction_tvlt import TvltFeatureExtractor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tvlt import (
						    TVLT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TvltForAudioVisualClassification,
						    TvltForPreTraining,
						    TvltModel,
						    TvltPreTrainedModel,
						)

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .image_processing_tvlt import TvltImageProcessor


else:
			import sys

			_lowerCamelCase :       Dict     					=    _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)