



"""simple docstring"""
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__SCREAMING_SNAKE_CASE  :						Any    							=      '''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e-img2img"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''


@dataclass
class 							lowerCamelCase_(   a__    ):





     '''simple docstring'''



     lowercase__   :       Union[PIL.Image.Image, np.ndarray]


class 							lowerCamelCase_(   a__    ):





     '''simple docstring'''



     def __init__(    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       ):
         super().__init__()

         self.register_modules(
             prior=lowerCAmelCase__				,       image_encoder=lowerCAmelCase__				,       image_processor=lowerCAmelCase__				,       scheduler=lowerCAmelCase__				,       renderer=lowerCAmelCase__				,       )

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   ):
         if latents is None:
             _lowerCamelCase        =				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}"""   )
             _lowerCamelCase        =				latents.to(lowerCAmelCase__   )

         _lowerCamelCase        =				latents * scheduler.init_noise_sigma
         return latents

     def 			snake_case__      (    self				,       lowerCamelCase__=0   ):
         if is_accelerate_available():
             from accelerate import cpu_offload
         else:
             raise ImportError('''Please install accelerate via `pip install accelerate`'''   )

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

         _lowerCamelCase        =				[self.image_encoder, self.prior]
         for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                 cpu_offload(lowerCAmelCase__				,       lowerCAmelCase__   )

     @property
     def 			snake_case__      (    self   ):
         if self.device != torch.device('''meta'''   ) or not hasattr(self.image_encoder				,       '''_hf_hook'''   ):
             return self.device
         for module in self.image_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 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       ):
         if isinstance(lowerCAmelCase__				,       lowerCAmelCase__   ) and isinstance(image[0]				,       torch.Tensor   ):
             _lowerCamelCase        =				torch.cat(lowerCAmelCase__				,       axis=0   ) if image[0].ndim == 4 else torch.stack(lowerCAmelCase__				,       axis=0   )

         if not isinstance(lowerCAmelCase__				,       torch.Tensor   ):
             _lowerCamelCase        =				self.image_processor(lowerCAmelCase__				,       return_tensors='''pt'''   ).pixel_values[0].unsqueeze(0   )

         _lowerCamelCase        =				image.to(dtype=self.image_encoder.dtype				,       device=lowerCAmelCase__   )

         _lowerCamelCase        =				self.image_encoder(lowerCAmelCase__   )["last_hidden_state"]
         _lowerCamelCase        =				image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

         _lowerCamelCase        =				image_embeds.repeat_interleave(lowerCAmelCase__				,       dim=0   )

         if do_classifier_free_guidance:
             _lowerCamelCase        =				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
             _lowerCamelCase        =				torch.cat([negative_image_embeds, image_embeds]   )

         return image_embeds





     @torch.no_grad()
     @replace_example_docstring(lowerCAmelCase__   )
     def __call__(    self				,       lowerCamelCase__				,       lowerCamelCase__ = 1				,       lowerCamelCase__ = 2_5				,       lowerCamelCase__ = None				,       lowerCamelCase__ = None				,       lowerCamelCase__ = 4.0				,       lowerCamelCase__ = 6_4				,       lowerCamelCase__ = "pil"				,       lowerCamelCase__ = True				,       ):

         if isinstance(lowerCAmelCase__				,       PIL.Image.Image   ):
             _lowerCamelCase        =				1
         elif isinstance(lowerCAmelCase__				,       torch.Tensor   ):
             _lowerCamelCase        =				image.shape[0]
         elif isinstance(lowerCAmelCase__				,       lowerCAmelCase__   ) and isinstance(image[0]				,       (torch.Tensor, PIL.Image.Image)   ):
             _lowerCamelCase        =				len(lowerCAmelCase__   )
         else:
             raise ValueError(
                 F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(lowerCAmelCase__   )}"""   )

         _lowerCamelCase        =				self._execution_device

         _lowerCamelCase        =				batch_size * num_images_per_prompt

         _lowerCamelCase        =				guidance_scale > 1.0
         _lowerCamelCase        =				self._encode_image(lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__   )

         # prior

         self.scheduler.set_timesteps(lowerCAmelCase__				,       device=lowerCAmelCase__   )
         _lowerCamelCase        =				self.scheduler.timesteps

         _lowerCamelCase        =				self.prior.config.num_embeddings
         _lowerCamelCase        =				self.prior.config.embedding_dim

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

             _lowerCamelCase        =				self.prior(
                 lowerCAmelCase__				,       timestep=lowerCAmelCase__				,       proj_embedding=lowerCAmelCase__				,       ).predicted_image_embedding

             # remove the variance
             _lowerCamelCase        =				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        =				noise_pred.chunk(2   )
                 _lowerCamelCase        =				noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

             _lowerCamelCase        =				self.scheduler.step(
                 lowerCAmelCase__				,       timestep=lowerCAmelCase__				,       sample=lowerCAmelCase__				,       ).prev_sample

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

         _lowerCamelCase        =				[]
         for i, latent in enumerate(lowerCAmelCase__   ):
             print()
             _lowerCamelCase        =				self.renderer.decode(
                 latent[None, :]				,       lowerCAmelCase__				,       size=lowerCAmelCase__				,       ray_batch_size=4_0_9_6				,       n_coarse_samples=6_4				,       n_fine_samples=1_2_8				,       )

             images.append(lowerCAmelCase__   )

         _lowerCamelCase        =				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}"""   )

         _lowerCamelCase        =				images.cpu().numpy()

         if output_type == "pil":
             _lowerCamelCase        =				[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 itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
			from transformers import WhisperFeatureExtractor

if is_torch_available():
			import torch

__SCREAMING_SNAKE_CASE  :						Dict    							=      random.Random()



def        lowerCAmelCase_(   lowercase_     :							Dict						,   lowercase_     :							int=1.0						,   lowercase_     :							str=None						,   lowercase_     :							Optional[int]=None							)	->       Any:
				if rng is None:
								_lowerCamelCase        =				global_rng

				_lowerCamelCase        =				[]
				for batch_idx in range(shape[0]							):
								values.append([]							)
								for _ in range(shape[1]							):
												values[-1].append(rng.random() * scale							)

				return values


@require_torch
@require_torchaudio
class 							lowerCamelCase_(   unittest.TestCase    ):





					'''simple docstring'''



					def __init__(    self				,       lowerCamelCase__				,       lowerCamelCase__=7				,       lowerCamelCase__=4_0_0				,       lowerCamelCase__=2_0_0_0				,       lowerCamelCase__=1_0				,       lowerCamelCase__=1_6_0				,       lowerCamelCase__=8				,       lowerCamelCase__=0.0				,       lowerCamelCase__=4_0_0_0				,       lowerCamelCase__=False				,       lowerCamelCase__=True				,       ):
									_lowerCamelCase        =				parent
									_lowerCamelCase        =				batch_size
									_lowerCamelCase        =				min_seq_length
									_lowerCamelCase        =				max_seq_length
									_lowerCamelCase        =				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									_lowerCamelCase        =				padding_value
									_lowerCamelCase        =				sampling_rate
									_lowerCamelCase        =				return_attention_mask
									_lowerCamelCase        =				do_normalize
									_lowerCamelCase        =				feature_size
									_lowerCamelCase        =				chunk_length
									_lowerCamelCase        =				hop_length

					def 			snake_case__      (    self   ):
									return {
									    "feature_size": self.feature_size,
									    "hop_length": self.hop_length,
									    "chunk_length": self.chunk_length,
									    "padding_value": self.padding_value,
									    "sampling_rate": self.sampling_rate,
									    "return_attention_mask": self.return_attention_mask,
									    "do_normalize": self.do_normalize,
									}





					def 			snake_case__      (    self				,       lowerCamelCase__=False				,       lowerCamelCase__=False   ):
									def _flatten(lowerCamelCase__   ):
													return list(itertools.chain(*lowerCamelCase__   )   )

									if equal_length:
													_lowerCamelCase        =				[floats_list((self.max_seq_length, self.feature_size)   ) for _ in range(self.batch_size   )]
									else:
													# make sure that inputs increase in size
													_lowerCamelCase        =				[
													    floats_list((x, self.feature_size)   )
													    for x in range(self.min_seq_length				,       self.max_seq_length				,       self.seq_length_diff   )
													]
									if numpify:
													_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for x in speech_inputs]
									return speech_inputs


@require_torch
@require_torchaudio
class 							lowerCamelCase_(   A__,				unittest.TestCase    ):





					'''simple docstring'''



					lowercase__   :       Optional[int]										= WhisperFeatureExtractor if is_speech_available() else None

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				WhisperFeatureExtractionTester(self   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

									with tempfile.TemporaryDirectory() as tmpdirname:
													_lowerCamelCase        =				feat_extract_first.save_pretrained(lowerCamelCase__   )[0]
													check_json_file_has_correct_format(lowerCamelCase__   )
													_lowerCamelCase        =				self.feature_extraction_class.from_pretrained(lowerCamelCase__   )

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

									with tempfile.TemporaryDirectory() as tmpdirname:
													_lowerCamelCase        =				os.path.join(lowerCamelCase__				,       '''feat_extract.json'''   )
													feat_extract_first.to_json_file(lowerCamelCase__   )
													_lowerCamelCase        =				self.feature_extraction_class.from_json_file(lowerCamelCase__   )

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									# Tests that all call wrap to encode_plus and batch_encode_plus
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									# create three inputs of length 800, 1000, and 1200
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(8_0_0				,       1_4_0_0				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

									# Test feature size
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       padding='''max_length'''				,       return_tensors='''np'''   ).input_features
									self.assertTrue(input_features.ndim == 3   )
									self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames   )
									self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size   )

									# Test not batched input
									_lowerCamelCase        =				feature_extractor(speech_inputs[0]				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(np_speech_inputs[0]				,       return_tensors='''np'''   ).input_features
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test batched
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test 2-D numpy arrays are batched.
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									_lowerCamelCase        =				np.asarray(lowerCamelCase__   )
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

									# Test truncation required
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(2_0_0				,       (feature_extractor.n_samples + 5_0_0)				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

									_lowerCamelCase        =				[x[: feature_extractor.n_samples] for x in speech_inputs]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs_truncated]

									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									for enc_seq_a, enc_seq_a in zip(lowerCamelCase__				,       lowerCamelCase__   ):
													self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )   )

					def 			snake_case__      (    self   ):
									import torch

									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				np.random.rand(1_0_0				,       3_2   ).astype(np.floataa   )
									_lowerCamelCase        =				np_speech_inputs.tolist()

									for inputs in [py_speech_inputs, np_speech_inputs]:
													_lowerCamelCase        =				feature_extractor.pad([{'''input_features''': inputs}]				,       return_tensors='''np'''   )
													self.assertTrue(np_processed.input_features.dtype == np.floataa   )
													_lowerCamelCase        =				feature_extractor.pad([{'''input_features''': inputs}]				,       return_tensors='''pt'''   )
													self.assertTrue(pt_processed.input_features.dtype == torch.floataa   )

					def 			snake_case__      (    self				,       lowerCamelCase__   ):
									_lowerCamelCase        =				load_dataset('''hf-internal-testing/librispeech_asr_dummy'''				,       '''clean'''				,       split='''validation'''   )
									# automatic decoding with librispeech
									_lowerCamelCase        =				ds.sort('''id'''   ).select(range(lowerCamelCase__   )   )[:num_samples]['''audio''']

									return [x["array"] for x in speech_samples]

					def 			snake_case__      (    self   ):
									# fmt: off
									_lowerCamelCase        =				torch.tensor(
									    [
									        0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
									        0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
									        0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
									        -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
									    ]   )
									# fmt: on

									_lowerCamelCase        =				self._load_datasamples(1   )
									_lowerCamelCase        =				WhisperFeatureExtractor()
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''pt'''   ).input_features
									self.assertEqual(input_features.shape				,       (1, 8_0, 3_0_0_0)   )
									self.assertTrue(torch.allclose(input_features[0, 0, :3_0]				,       lowerCamelCase__				,       atol=1e-4   )   )





					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				self._load_datasamples(1   )[0]
									_lowerCamelCase        =				((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
									_lowerCamelCase        =				feat_extract.zero_mean_unit_var_norm([audio]				,       attention_mask=lowerCamelCase__   )[0]

									self.assertTrue(np.all(np.mean(lowerCamelCase__   ) < 1e-3   )   )
									self.assertTrue(np.all(np.abs(np.var(lowerCamelCase__   ) - 1   ) < 1e-3   )   )
