



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


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

lowerCAmelCase__		:					Tuple							='''
    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        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




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







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A				,							_A				,							_A				,							_A				,							):







													'''simple docstring'''

													super().__init__()

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






						def 	_A     (   self				,							_A				,							_A				,							_A				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													if latents is None:
																				__SCREAMING_SNAKE_CASE									= randn_tensor(_A				,							generator=_A				,							device=_A				,							dtype=_A		)
													else:
																				if latents.shape != shape:
																											raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""		)
																				__SCREAMING_SNAKE_CASE									= latents.to(_A		)

													__SCREAMING_SNAKE_CASE									= latents * scheduler.init_noise_sigma
													return latents






						def 	_A     (   self				,							_A=0		):







													'''simple docstring'''

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

													__SCREAMING_SNAKE_CASE									= torch.device(f"""cuda:{gpu_id}"""		)

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






						@property
						def 	_A     (   self		):







													'''simple docstring'''

													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(_A				,							'_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				,							_A				,							_A				,							_A				,							_A				,							):







													'''simple docstring'''

													if isinstance(_A				,							_A		) and isinstance(image[0]				,							torch.Tensor		):
																				__SCREAMING_SNAKE_CASE									= torch.cat(_A				,							axis=0		) if image[0].ndim == 4 else torch.stack(_A				,							axis=0		)

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

													__SCREAMING_SNAKE_CASE									= image.to(dtype=self.image_encoder.dtype				,							device=_A		)

													__SCREAMING_SNAKE_CASE									= self.image_encoder(_A		)['last_hidden_state']
													__SCREAMING_SNAKE_CASE									= image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

													__SCREAMING_SNAKE_CASE									= image_embeds.repeat_interleave(_A				,							dim=0		)

													if do_classifier_free_guidance:
																				__SCREAMING_SNAKE_CASE									= torch.zeros_like(_A		)

																				# 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
																				__SCREAMING_SNAKE_CASE									= torch.cat([negative_image_embeds, image_embeds]		)

													return image_embeds






						@torch.no_grad()
						@replace_example_docstring(_A		)
						def __call__(   self				,							_A				,							_A = 1				,							_A = 25				,							_A = None				,							_A = None				,							_A = 4.0				,							_A = 64				,							_A = "pil"				,							_A = True				,							):







													'''simple docstring'''

													if isinstance(_A				,							PIL.Image.Image		):
																				__SCREAMING_SNAKE_CASE									= 1
													elif isinstance(_A				,							torch.Tensor		):
																				__SCREAMING_SNAKE_CASE									= image.shape[0]
													elif isinstance(_A				,							_A		) and isinstance(image[0]				,							(torch.Tensor, PIL.Image.Image)		):
																				__SCREAMING_SNAKE_CASE									= len(_A		)
													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(_A		)}"""		)

													__SCREAMING_SNAKE_CASE									= self._execution_device

													__SCREAMING_SNAKE_CASE									= batch_size * num_images_per_prompt

													__SCREAMING_SNAKE_CASE									= guidance_scale > 1.0
													__SCREAMING_SNAKE_CASE									= self._encode_image(_A				,							_A				,							_A				,							_A		)

													# prior

													self.scheduler.set_timesteps(_A				,							device=_A		)
													__SCREAMING_SNAKE_CASE									= self.scheduler.timesteps

													__SCREAMING_SNAKE_CASE									= self.prior.config.num_embeddings
													__SCREAMING_SNAKE_CASE									= self.prior.config.embedding_dim

													__SCREAMING_SNAKE_CASE									= self.prepare_latents(
													    (batch_size, num_embeddings * embedding_dim)				,							image_embeds.dtype				,							_A				,							_A				,							_A				,							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
													__SCREAMING_SNAKE_CASE									= latents.reshape(latents.shape[0]				,							_A				,							_A		)

													for i, t in enumerate(self.progress_bar(_A		)		):
																				# expand the latents if we are doing classifier free guidance
																				__SCREAMING_SNAKE_CASE									= torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
																				__SCREAMING_SNAKE_CASE									= self.scheduler.scale_model_input(_A				,							_A		)

																				__SCREAMING_SNAKE_CASE									= self.prior(
																				    _A				,							timestep=_A				,							proj_embedding=_A				,							).predicted_image_embedding

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

																				__SCREAMING_SNAKE_CASE									= self.scheduler.step(
																				    _A				,							timestep=_A				,							sample=_A				,							).prev_sample

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

													__SCREAMING_SNAKE_CASE									= []
													for i, latent in enumerate(_A		):
																				print()
																				__SCREAMING_SNAKE_CASE									= self.renderer.decode(
																				    latent[None, :]				,							_A				,							size=_A				,							ray_batch_size=4_096				,							n_coarse_samples=64				,							n_fine_samples=128				,							)

																				images.append(_A		)

													__SCREAMING_SNAKE_CASE									= torch.stack(_A		)

													if output_type not in ["np", "pil"]:
																				raise ValueError(f"""Only the output types `pil` and `np` are supported not output_type={output_type}"""		)

													__SCREAMING_SNAKE_CASE									= images.cpu().numpy()

													if output_type == "pil":
																				__SCREAMING_SNAKE_CASE									= [self.numpy_to_pil(_A		) 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=_A		)











import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase__		:					Dict							=random.Random()

if is_torch_available():
			import torch






def      __lowercase       (			a__							,       a__=1.0							,       a__=None							,       a__=None       )    ->			Any:
							if rng is None:
														__SCREAMING_SNAKE_CASE									= global_rng

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

							return values

class        UpperCAmelCase_  (       unittest.TestCase	):

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A=7				,							_A=400				,							_A=2_000				,							_A=1				,							_A=0.0				,							_A=16_000				,							_A=True				,							_A=True				,							):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= parent
													__SCREAMING_SNAKE_CASE									= batch_size
													__SCREAMING_SNAKE_CASE									= min_seq_length
													__SCREAMING_SNAKE_CASE									= max_seq_length
													__SCREAMING_SNAKE_CASE									= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
													__SCREAMING_SNAKE_CASE									= feature_size
													__SCREAMING_SNAKE_CASE									= padding_value
													__SCREAMING_SNAKE_CASE									= sampling_rate
													__SCREAMING_SNAKE_CASE									= return_attention_mask
													__SCREAMING_SNAKE_CASE									= do_normalize






						def 	_A     (   self		):







													'''simple docstring'''

													return {
													    "feature_size": self.feature_size,
													    "padding_value": self.padding_value,
													    "sampling_rate": self.sampling_rate,
													    "return_attention_mask": self.return_attention_mask,
													    "do_normalize": self.do_normalize,
													}






						def 	_A     (   self				,							_A=False				,							_A=False		):







													'''simple docstring'''

													def _flatten(_A		):
																				return list(itertools.chain(*_A		)		)

													if equal_length:
																				__SCREAMING_SNAKE_CASE									= floats_list((self.batch_size, self.max_seq_length)		)
													else:
																				# make sure that inputs increase in size
																				__SCREAMING_SNAKE_CASE									= [
																				    _flatten(floats_list((x, self.feature_size)		)		)
																				    for x in range(self.min_seq_length				,							self.max_seq_length				,							self.seq_length_diff		)
																				]

													if numpify:
																				__SCREAMING_SNAKE_CASE									= [np.asarray(_A		) for x in speech_inputs]

													return speech_inputs







@require_torch
@require_torchaudio
class        UpperCAmelCase_  (       UpperCamelCase_   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			Optional[int]      =  ASTFeatureExtractor






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= ASTFeatureExtractionTester(self		)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
													# create three inputs of length 800, 1000, and 1200
													__SCREAMING_SNAKE_CASE									= [floats_list((1, x)		)[0] for x in range(800				,							1_400				,							200		)]
													__SCREAMING_SNAKE_CASE									= [np.asarray(_A		) for speech_input in speech_inputs]

													# Test not batched input
													__SCREAMING_SNAKE_CASE									= feat_extract(speech_inputs[0]				,							return_tensors='np'		).input_values
													__SCREAMING_SNAKE_CASE									= feat_extract(np_speech_inputs[0]				,							return_tensors='np'		).input_values
													self.assertTrue(np.allclose(_A				,							_A				,							atol=1e-3		)		)

													# Test batched
													__SCREAMING_SNAKE_CASE									= feat_extract(_A				,							padding=_A				,							return_tensors='np'		).input_values
													__SCREAMING_SNAKE_CASE									= feat_extract(_A				,							padding=_A				,							return_tensors='np'		).input_values
													for enc_seq_a, enc_seq_a in zip(_A				,							_A		):
																				self.assertTrue(np.allclose(_A				,							_A				,							atol=1e-3		)		)

													# Test 2-D numpy arrays are batched.
													__SCREAMING_SNAKE_CASE									= [floats_list((1, x)		)[0] for x in (800, 800, 800)]
													__SCREAMING_SNAKE_CASE									= np.asarray(_A		)
													__SCREAMING_SNAKE_CASE									= feat_extract(_A				,							return_tensors='np'		).input_values
													__SCREAMING_SNAKE_CASE									= feat_extract(_A				,							return_tensors='np'		).input_values
													for enc_seq_a, enc_seq_a in zip(_A				,							_A		):
																				self.assertTrue(np.allclose(_A				,							_A				,							atol=1e-3		)		)






						@require_torch
						def 	_A     (   self		):







													'''simple docstring'''

													import torch

													__SCREAMING_SNAKE_CASE									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
													__SCREAMING_SNAKE_CASE									= np.random.rand(100		).astype(np.floataa		)
													__SCREAMING_SNAKE_CASE									= np_speech_inputs.tolist()

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






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													from datasets import load_dataset

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

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






						@require_torch
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= torch.tensor(
													    [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
													     -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
													     -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
													     -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]		)
													# fmt: on

													__SCREAMING_SNAKE_CASE									= self._load_datasamples(1		)
													__SCREAMING_SNAKE_CASE									= ASTFeatureExtractor()
													__SCREAMING_SNAKE_CASE									= feature_extractor(_A				,							return_tensors='pt'		).input_values
													self.assertEquals(input_values.shape				,							(1, 1_024, 128)		)
													self.assertTrue(torch.allclose(input_values[0, 0, :30]				,							_A				,							atol=1e-4		)		)






