
'''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 			lowerCAmelCase__ (							UpperCamelCase							):



  '''simple docstring'''






  _UpperCamelCase							=			42



class 			lowerCAmelCase__ (							UpperCamelCase							):



  '''simple docstring'''






  def __init__(self	:			Optional[Any]						,			lowerCAmelCase_	:			PriorTransformer						,			lowerCAmelCase_	:			CLIPTextModelWithProjection						,			lowerCAmelCase_	:			CLIPTokenizer						,			lowerCAmelCase_	:			HeunDiscreteScheduler						,			lowerCAmelCase_	:			ShapERenderer						,			) ->							Optional[Any]:
        super().__init__()

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

  def 		_lowerCamelCase						(self	:			Union[str, Any]						,			lowerCAmelCase_	:			Optional[int]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			Optional[int]     ) ->							Optional[int]:
        if latents is None:
              snake_case_    							=				randn_tensor(lowerCAmelCase_						,			generator=lowerCAmelCase_						,			device=lowerCAmelCase_						,			dtype=lowerCAmelCase_     )
        else:
              if latents.shape != shape:
                    raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''     )
              snake_case_    							=				latents.to(lowerCAmelCase_     )

        snake_case_    							=				latents * scheduler.init_noise_sigma
        return latents

  def 		_lowerCamelCase						(self	:			str						,			lowerCAmelCase_	:			str=0     ) ->							List[str]:
        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(lowerCAmelCase_						,			lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			Dict						,			lowerCAmelCase_	:			Union[str, Any]=0     ) ->							str:
        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=lowerCAmelCase_     )
              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(lowerCAmelCase_						,			lowerCAmelCase_						,			prev_module_hook=lowerCAmelCase_     )

        if self.safety_checker is not None:
              snake_case_							,						snake_case_    							=				cpu_offload_with_hook(self.safety_checker						,			lowerCAmelCase_						,			prev_module_hook=lowerCAmelCase_     )

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

  @property
  def 		_lowerCamelCase						(self	:			List[str]     ) ->							Union[str, Any]:
        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(lowerCAmelCase_						,			"_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	:			Dict						,			lowerCAmelCase_	:			Optional[Any]						,			lowerCAmelCase_	:			Any						,			lowerCAmelCase_	:			List[Any]						,			lowerCAmelCase_	:			Any						,			) ->							int:
        len(lowerCAmelCase_     ) if isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ) 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(
            lowerCAmelCase_						,			padding="max_length"						,			max_length=self.tokenizer.model_max_length						,			truncation=lowerCAmelCase_						,			return_tensors="pt"						,			)
        snake_case_    							=				text_inputs.input_ids
        snake_case_    							=				self.tokenizer(lowerCAmelCase_						,			padding="longest"						,			return_tensors="pt"     ).input_ids

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

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

        if do_classifier_free_guidance:
              snake_case_    							=				torch.zeros_like(lowerCAmelCase_     )

              # 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(lowerCAmelCase_     )
  def __call__(self	:			int						,			lowerCAmelCase_	:			str						,			lowerCAmelCase_	:			int = 1						,			lowerCAmelCase_	:			int = 25						,			lowerCAmelCase_	:			Optional[Union[torch.Generator, List[torch.Generator]]] = None						,			lowerCAmelCase_	:			Optional[torch.FloatTensor] = None						,			lowerCAmelCase_	:			float = 4.0						,			lowerCAmelCase_	:			int = 64						,			lowerCAmelCase_	:			Optional[str] = "pil"						,			lowerCAmelCase_	:			bool = True						,			) ->							Dict:

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

        snake_case_    							=				self._execution_device

        snake_case_    							=				batch_size * num_images_per_prompt

        snake_case_    							=				guidance_scale > 1.0
        snake_case_    							=				self._encode_prompt(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_     )

        # prior

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

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

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

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

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

        snake_case_    							=				torch.stack(lowerCAmelCase_     )

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



'''simple docstring'''





import shutil
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import SpeechaTextTokenizer, is_speech_available
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, require_torchaudio
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_speech_to_text import floats_list


if is_speech_available():
     from transformers import SpeechaTextFeatureExtractor, SpeechaTextProcessor


A							     = get_tests_dir("fixtures/test_sentencepiece.model")



@require_torch
@require_torchaudio
@require_sentencepiece
class 			lowerCAmelCase__ (							unittest.TestCase							):



  '''simple docstring'''






  def 		_lowerCamelCase						(self	:			List[str]     ) ->							List[str]:
        snake_case_    							=				tempfile.mkdtemp()

        snake_case_    							=				["<s>", "<pad>", "</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est"]
        snake_case_    							=				dict(zip(lowerCAmelCase_						,			range(len(lowerCAmelCase_     )     )     )     )
        snake_case_    							=				Path(self.tmpdirname     )
        save_json(lowerCAmelCase_						,			save_dir / VOCAB_FILES_NAMES["vocab_file"]     )
        if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
              copyfile(lowerCAmelCase_						,			save_dir / VOCAB_FILES_NAMES["spm_file"]     )

        snake_case_    							=				SpeechaTextTokenizer.from_pretrained(self.tmpdirname     )
        tokenizer.save_pretrained(self.tmpdirname     )

        snake_case_    							=				{
            "feature_size": 24,
            "num_mel_bins": 24,
            "padding_value": 0.0,
            "sampling_rate": 1_60_00,
            "return_attention_mask": False,
            "do_normalize": True,
        }
        save_json(lowerCAmelCase_						,			save_dir / FEATURE_EXTRACTOR_NAME     )

  def 		_lowerCamelCase						(self	:			Dict						,			**lowerCAmelCase_	:			Any     ) ->							Union[str, Any]:
        return SpeechaTextTokenizer.from_pretrained(self.tmpdirname						,			**lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			List[str]						,			**lowerCAmelCase_	:			List[str]     ) ->							Any:
        return SpeechaTextFeatureExtractor.from_pretrained(self.tmpdirname						,			**lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			int     ) ->							str:
        shutil.rmtree(self.tmpdirname     )

  def 		_lowerCamelCase						(self	:			List[Any]     ) ->							Optional[Any]:
        snake_case_    							=				self.get_tokenizer()
        snake_case_    							=				self.get_feature_extractor()

        snake_case_    							=				SpeechaTextProcessor(tokenizer=lowerCAmelCase_						,			feature_extractor=lowerCAmelCase_     )

        processor.save_pretrained(self.tmpdirname     )
        snake_case_    							=				SpeechaTextProcessor.from_pretrained(self.tmpdirname     )

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

        self.assertEqual(processor.feature_extractor.to_json_string()						,			feature_extractor.to_json_string()     )
        self.assertIsInstance(processor.feature_extractor						,			lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			str     ) ->							int:
        snake_case_    							=				SpeechaTextProcessor(
            tokenizer=self.get_tokenizer()						,			feature_extractor=self.get_feature_extractor()     )
        processor.save_pretrained(self.tmpdirname     )

        snake_case_    							=				self.get_tokenizer(bos_token="(BOS)"						,			eos_token="(EOS)"     )
        snake_case_    							=				self.get_feature_extractor(do_normalize=lowerCAmelCase_						,			padding_value=1.0     )

        snake_case_    							=				SpeechaTextProcessor.from_pretrained(
            self.tmpdirname						,			bos_token="(BOS)"						,			eos_token="(EOS)"						,			do_normalize=lowerCAmelCase_						,			padding_value=1.0     )

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

        self.assertEqual(processor.feature_extractor.to_json_string()						,			feature_extractor_add_kwargs.to_json_string()     )
        self.assertIsInstance(processor.feature_extractor						,			lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			Tuple     ) ->							Optional[Any]:
        snake_case_    							=				self.get_feature_extractor()
        snake_case_    							=				self.get_tokenizer()

        snake_case_    							=				SpeechaTextProcessor(tokenizer=lowerCAmelCase_						,			feature_extractor=lowerCAmelCase_     )

        snake_case_    							=				floats_list((3, 10_00)     )

        snake_case_    							=				feature_extractor(lowerCAmelCase_						,			return_tensors="np"     )
        snake_case_    							=				processor(lowerCAmelCase_						,			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	:			Union[str, Any]     ) ->							int:
        snake_case_    							=				self.get_feature_extractor()
        snake_case_    							=				self.get_tokenizer()

        snake_case_    							=				SpeechaTextProcessor(tokenizer=lowerCAmelCase_						,			feature_extractor=lowerCAmelCase_     )

        snake_case_    							=				"This is a test string"

        snake_case_    							=				processor(text=lowerCAmelCase_     )

        snake_case_    							=				tokenizer(lowerCAmelCase_     )

        for key in encoded_tok.keys():
              self.assertListEqual(encoded_tok[key]						,			encoded_processor[key]     )

  def 		_lowerCamelCase						(self	:			Union[str, Any]     ) ->							int:
        snake_case_    							=				self.get_feature_extractor()
        snake_case_    							=				self.get_tokenizer()

        snake_case_    							=				SpeechaTextProcessor(tokenizer=lowerCAmelCase_						,			feature_extractor=lowerCAmelCase_     )

        snake_case_    							=				[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

        snake_case_    							=				processor.batch_decode(lowerCAmelCase_     )
        snake_case_    							=				tokenizer.batch_decode(lowerCAmelCase_     )

        self.assertListEqual(lowerCAmelCase_						,			lowerCAmelCase_     )


  def 		_lowerCamelCase						(self	:			int     ) ->							int:
        snake_case_    							=				self.get_feature_extractor()
        snake_case_    							=				self.get_tokenizer()

        snake_case_    							=				SpeechaTextProcessor(tokenizer=lowerCAmelCase_						,			feature_extractor=lowerCAmelCase_     )

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

