




"""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


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

a_            =   '\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        UpperCAmelCase_  (	snake_case						):
		UpperCamelCase									=42


class        UpperCAmelCase_  (	snake_case						):
		def __init__(		self							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		)		->   Optional[Any]:
					super().__init__()

					self.register_modules(
					    prior=UpperCamelCase_							,		text_encoder=UpperCamelCase_							,		tokenizer=UpperCamelCase_							,		scheduler=UpperCamelCase_							,		renderer=UpperCamelCase_							,		)
		def 					_lowerCamelCase    (		self							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_   )		->   Optional[int]:
					if latents is None:
								__lowercase	:       Union[str, Any]				=   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}"""   )
								__lowercase	:       Tuple				=   latents.to(UpperCamelCase_   )

					__lowercase	:       Dict				=   latents * scheduler.init_noise_sigma
					return latents
		def 					_lowerCamelCase    (		self							,		UpperCamelCase_=0   )		->   List[Any]:
					if is_accelerate_available():
								from accelerate import cpu_offload
					else:
								raise ImportError('''Please install accelerate via `pip install accelerate`'''   )

					__lowercase	:       int				=   torch.device(F"""cuda:{gpu_id}"""   )

					__lowercase	:       List[str]				=   [self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
								if cpu_offloaded_model is not None:
											cpu_offload(UpperCamelCase_							,		UpperCamelCase_   )
		def 					_lowerCamelCase    (		self							,		UpperCamelCase_=0   )		->   int:
					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.'''   )

					__lowercase	:       Optional[Any]				=   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)

					__lowercase	:       Optional[int]				=   None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
								__lowercase	:       List[str]				=   cpu_offload_with_hook(UpperCamelCase_							,		UpperCamelCase_							,		prev_module_hook=UpperCamelCase_   )

					if self.safety_checker is not None:
								__lowercase	:       Any				=   cpu_offload_with_hook(self.safety_checker							,		UpperCamelCase_							,		prev_module_hook=UpperCamelCase_   )

					# We'll offload the last model manually.
					__lowercase	:       str				=   hook
		@property
		def 					_lowerCamelCase    (		self   )		->   int:
					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 					_lowerCamelCase    (		self							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		)		->   int:
					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
					__lowercase	:       Optional[int]				=   0
					# get prompt text embeddings
					__lowercase	:       Any				=   self.tokenizer(
					    UpperCamelCase_							,		padding='''max_length'''							,		max_length=self.tokenizer.model_max_length							,		truncation=UpperCamelCase_							,		return_tensors='''pt'''							,		)
					__lowercase	:       Any				=   text_inputs.input_ids
					__lowercase	:       List[Any]				=   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_   ):
								__lowercase	:       int				=   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}"""   )

					__lowercase	:       Any				=   self.text_encoder(text_input_ids.to(UpperCamelCase_   )   )
					__lowercase	:       Tuple				=   text_encoder_output.text_embeds

					__lowercase	:       int				=   prompt_embeds.repeat_interleave(UpperCamelCase_							,		dim=0   )
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					__lowercase	:       Dict				=   prompt_embeds / torch.linalg.norm(UpperCamelCase_							,		dim=-1							,		keepdim=UpperCamelCase_   )

					if do_classifier_free_guidance:
								__lowercase	:       Union[str, 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
								__lowercase	:       Optional[int]				=   torch.cat([negative_prompt_embeds, prompt_embeds]   )

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

					return prompt_embeds
		@torch.no_grad()
		@replace_example_docstring(UpperCamelCase_   )
		def __call__(		self							,		UpperCamelCase_							,		UpperCamelCase_ = 1							,		UpperCamelCase_ = 25							,		UpperCamelCase_ = None							,		UpperCamelCase_ = None							,		UpperCamelCase_ = 4.0							,		UpperCamelCase_ = 64							,		UpperCamelCase_ = "pil"							,		UpperCamelCase_ = True							,		)		->   int:

					if isinstance(UpperCamelCase_							,		UpperCamelCase_   ):
								__lowercase	:       List[str]				=   1
					elif isinstance(UpperCamelCase_							,		UpperCamelCase_   ):
								__lowercase	:       Tuple				=   len(UpperCamelCase_   )
					else:
								raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase_   )}"""   )

					__lowercase	:       List[Any]				=   self._execution_device

					__lowercase	:       Dict				=   batch_size * num_images_per_prompt

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

					# prior

					self.scheduler.set_timesteps(UpperCamelCase_							,		device=UpperCamelCase_   )
					__lowercase	:       Dict				=   self.scheduler.timesteps

					__lowercase	:       Union[str, Any]				=   self.prior.config.num_embeddings
					__lowercase	:       Dict				=   self.prior.config.embedding_dim

					__lowercase	:       List[Any]				=   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
					__lowercase	:       List[Any]				=   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
								__lowercase	:       List[Any]				=   torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
								__lowercase	:       Tuple				=   self.scheduler.scale_model_input(UpperCamelCase_							,		UpperCamelCase_   )

								__lowercase	:       Dict				=   self.prior(
								    UpperCamelCase_							,		timestep=UpperCamelCase_							,		proj_embedding=UpperCamelCase_							,		).predicted_image_embedding

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

								__lowercase	:       Any				=   self.scheduler.step(
								    UpperCamelCase_							,		timestep=UpperCamelCase_							,		sample=UpperCamelCase_							,		).prev_sample

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

					__lowercase	:       Tuple				=   []
					for i, latent in enumerate(UpperCamelCase_   ):
								__lowercase	:       List[str]				=   self.renderer.decode(
								    latent[None, :]							,		UpperCamelCase_							,		size=UpperCamelCase_							,		ray_batch_size=40_96							,		n_coarse_samples=64							,		n_fine_samples=1_28							,		)
								images.append(UpperCamelCase_   )

					__lowercase	:       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}"""   )

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

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









"""simple docstring"""




import json
import os
import shutil
import tempfile
import unittest

from transformers import is_speech_available, is_torch_available
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_torch
from transformers.utils import FEATURE_EXTRACTOR_NAME


if is_speech_available() and is_torch_available():
			from transformers import SpeechTaFeatureExtractor, SpeechTaProcessor

			from .test_feature_extraction_speechta import floats_list


a_            =   get_tests_dir('fixtures/test_sentencepiece_bpe_char.model')

@require_torch
class        UpperCAmelCase_  (	unittest.TestCase						):
		def 					_lowerCamelCase    (		self   )		->   Dict:
					__lowercase	:       Union[str, Any]				=   tempfile.mkdtemp()

					__lowercase	:       List[str]				=   SpeechTaTokenizer(UpperCamelCase_   )
					tokenizer.save_pretrained(self.tmpdirname   )

					__lowercase	:       Dict				=   {
					    '''feature_size''': 1,
					    '''padding_value''': 0.0,
					    '''sampling_rate''': 1_60_00,
					    '''do_normalize''': False,
					    '''num_mel_bins''': 80,
					    '''hop_length''': 16,
					    '''win_length''': 64,
					    '''win_function''': '''hann_window''',
					    '''fmin''': 80,
					    '''fmax''': 76_00,
					    '''mel_floor''': 1E-10,
					    '''reduction_factor''': 2,
					    '''return_attention_mask''': True,
					}

					__lowercase	:       List[Any]				=   os.path.join(self.tmpdirname							,		UpperCamelCase_   )
					with open(self.feature_extraction_file							,		'''w'''							,		encoding='''utf-8'''   ) as fp:
								fp.write(json.dumps(UpperCamelCase_   ) + '''\n'''   )
		def 					_lowerCamelCase    (		self							,		**UpperCamelCase_   )		->   Union[str, Any]:
					return SpeechTaTokenizer.from_pretrained(self.tmpdirname							,		**UpperCamelCase_   )
		def 					_lowerCamelCase    (		self							,		**UpperCamelCase_   )		->   Optional[Any]:
					return SpeechTaFeatureExtractor.from_pretrained(self.tmpdirname							,		**UpperCamelCase_   )
		def 					_lowerCamelCase    (		self   )		->   Any:
					shutil.rmtree(self.tmpdirname   )
		def 					_lowerCamelCase    (		self   )		->   Union[str, Any]:
					__lowercase	:       List[str]				=   self.get_tokenizer()
					__lowercase	:       int				=   self.get_feature_extractor()

					__lowercase	:       Any				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					processor.save_pretrained(self.tmpdirname   )
					__lowercase	:       List[Any]				=   SpeechTaProcessor.from_pretrained(self.tmpdirname   )

					self.assertEqual(processor.tokenizer.get_vocab()							,		tokenizer.get_vocab()   )
					self.assertIsInstance(processor.tokenizer							,		UpperCamelCase_   )

					self.assertEqual(processor.feature_extractor.to_json_string()							,		feature_extractor.to_json_string()   )
					self.assertIsInstance(processor.feature_extractor							,		UpperCamelCase_   )
		def 					_lowerCamelCase    (		self   )		->   Optional[Any]:
					__lowercase	:       Optional[int]				=   SpeechTaProcessor(tokenizer=self.get_tokenizer()							,		feature_extractor=self.get_feature_extractor()   )
					processor.save_pretrained(self.tmpdirname   )

					__lowercase	:       str				=   self.get_tokenizer(bos_token='''(BOS)'''							,		eos_token='''(EOS)'''   )
					__lowercase	:       Dict				=   self.get_feature_extractor(do_normalize=UpperCamelCase_							,		padding_value=1.0   )

					__lowercase	:       Tuple				=   SpeechTaProcessor.from_pretrained(
					    self.tmpdirname							,		bos_token='''(BOS)'''							,		eos_token='''(EOS)'''							,		do_normalize=UpperCamelCase_							,		padding_value=1.0   )

					self.assertEqual(processor.tokenizer.get_vocab()							,		tokenizer_add_kwargs.get_vocab()   )
					self.assertIsInstance(processor.tokenizer							,		UpperCamelCase_   )

					self.assertEqual(processor.feature_extractor.to_json_string()							,		feature_extractor_add_kwargs.to_json_string()   )
					self.assertIsInstance(processor.feature_extractor							,		UpperCamelCase_   )
		def 					_lowerCamelCase    (		self   )		->   List[str]:
					__lowercase	:       Optional[Any]				=   self.get_feature_extractor()
					__lowercase	:       Optional[Any]				=   self.get_tokenizer()

					__lowercase	:       Union[str, Any]				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					__lowercase	:       int				=   floats_list((3, 10_00)   )

					__lowercase	:       str				=   feature_extractor(audio=UpperCamelCase_							,		return_tensors='''np'''   )
					__lowercase	:       Dict				=   processor(audio=UpperCamelCase_							,		return_tensors='''np'''   )

					for key in input_feat_extract.keys():
								self.assertAlmostEqual(input_feat_extract[key].sum()							,		input_processor[key].sum()							,		delta=1E-2   )
		def 					_lowerCamelCase    (		self   )		->   List[Any]:
					__lowercase	:       str				=   self.get_feature_extractor()
					__lowercase	:       str				=   self.get_tokenizer()

					__lowercase	:       Union[str, Any]				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					__lowercase	:       Optional[int]				=   floats_list((3, 10_00)   )

					__lowercase	:       List[str]				=   feature_extractor(audio_target=UpperCamelCase_							,		return_tensors='''np'''   )
					__lowercase	:       List[str]				=   processor(audio_target=UpperCamelCase_							,		return_tensors='''np'''   )

					for key in input_feat_extract.keys():
								self.assertAlmostEqual(input_feat_extract[key].sum()							,		input_processor[key].sum()							,		delta=1E-2   )
		def 					_lowerCamelCase    (		self   )		->   Any:
					__lowercase	:       List[Any]				=   self.get_feature_extractor()
					__lowercase	:       List[str]				=   self.get_tokenizer()

					__lowercase	:       Union[str, Any]				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					__lowercase	:       List[str]				=   '''This is a test string'''

					__lowercase	:       Any				=   processor(text=UpperCamelCase_   )
					__lowercase	:       Optional[int]				=   tokenizer(UpperCamelCase_   )

					for key in encoded_tok.keys():
								self.assertListEqual(encoded_tok[key]							,		encoded_processor[key]   )
		def 					_lowerCamelCase    (		self   )		->   str:
					__lowercase	:       int				=   self.get_feature_extractor()
					__lowercase	:       List[str]				=   self.get_tokenizer()

					__lowercase	:       List[Any]				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					__lowercase	:       Union[str, Any]				=   '''This is a test string'''

					__lowercase	:       Tuple				=   processor(text_target=UpperCamelCase_   )
					__lowercase	:       Optional[int]				=   tokenizer(UpperCamelCase_   )

					for key in encoded_tok.keys():
								self.assertListEqual(encoded_tok[key]							,		encoded_processor[key]   )
		def 					_lowerCamelCase    (		self   )		->   Optional[Any]:
					__lowercase	:       Optional[int]				=   self.get_feature_extractor()
					__lowercase	:       str				=   self.get_tokenizer()

					__lowercase	:       int				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					__lowercase	:       Optional[Any]				=   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

					__lowercase	:       str				=   processor.batch_decode(UpperCamelCase_   )
					__lowercase	:       int				=   tokenizer.batch_decode(UpperCamelCase_   )

					self.assertListEqual(UpperCamelCase_							,		UpperCamelCase_   )
		def 					_lowerCamelCase    (		self   )		->   Optional[int]:
					__lowercase	:       Union[str, Any]				=   self.get_feature_extractor()
					__lowercase	:       int				=   self.get_tokenizer()

					__lowercase	:       Optional[int]				=   SpeechTaProcessor(tokenizer=UpperCamelCase_							,		feature_extractor=UpperCamelCase_   )

					self.assertListEqual(
					    processor.model_input_names							,		feature_extractor.model_input_names							,		msg='''`processor` and `feature_extractor` model input names do not match'''							,		)



