
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


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

_A  =	"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n"





@dataclass
class       _lowerCAmelCase   (      __a			):
				_lowercase     						=42





class       _lowerCAmelCase   (      __a			):




				def __init__(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							)							-> str:
							super().__init__()

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




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> List[str]:
							if latents is None:
										lowerCAmelCase_         =      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}"""	)
										lowerCAmelCase_         =      latents.to(_UpperCamelCase	)

							lowerCAmelCase_         =      latents * scheduler.init_noise_sigma
							return latents




				def 	__a		(   self							,							_UpperCamelCase=0	)							-> Dict:
							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(_UpperCamelCase							,							_UpperCamelCase	)




				@property
				def 	__a		(   self	)							-> Any:
							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(_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 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							)							-> Any:
							if isinstance(_UpperCamelCase							,							_UpperCamelCase	) and isinstance(image[0]							,							torch.Tensor	):
										lowerCAmelCase_         =      torch.cat(_UpperCamelCase							,							axis=0	) if image[0].ndim == 4 else torch.stack(_UpperCamelCase							,							axis=0	)

							if not isinstance(_UpperCamelCase							,							torch.Tensor	):
										lowerCAmelCase_         =      self.image_processor(_UpperCamelCase							,							return_tensors="pt"	).pixel_values[0].unsqueeze(0	)

							lowerCAmelCase_         =      image.to(dtype=self.image_encoder.dtype							,							device=_UpperCamelCase	)

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

							lowerCAmelCase_         =      image_embeds.repeat_interleave(_UpperCamelCase							,							dim=0	)

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

							return image_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							,							)							-> Optional[int]:

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

							lowerCAmelCase_         =      self._execution_device

							lowerCAmelCase_         =      batch_size * num_images_per_prompt

							lowerCAmelCase_         =      guidance_scale > 1.0
							lowerCAmelCase_         =      self._encode_image(_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)

							# prior

							self.scheduler.set_timesteps(_UpperCamelCase							,							device=_UpperCamelCase	)
							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							,							_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
							lowerCAmelCase_         =      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
										lowerCAmelCase_         =      torch.cat([latents] * 2	) if do_classifier_free_guidance else latents
										lowerCAmelCase_         =      self.scheduler.scale_model_input(_UpperCamelCase							,							_UpperCamelCase	)

										lowerCAmelCase_         =      self.prior(
										    _UpperCamelCase							,							timestep=_UpperCamelCase							,							proj_embedding=_UpperCamelCase							,							).predicted_image_embedding

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

										lowerCAmelCase_         =      self.scheduler.step(
										    _UpperCamelCase							,							timestep=_UpperCamelCase							,							sample=_UpperCamelCase							,							).prev_sample

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

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

										images.append(_UpperCamelCase	)

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

							lowerCAmelCase_         =      images.cpu().numpy()

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





from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
			import tensorflow as tf

			from transformers import (
			    TFDebertaVaForMaskedLM,
			    TFDebertaVaForQuestionAnswering,
			    TFDebertaVaForSequenceClassification,
			    TFDebertaVaForTokenClassification,
			    TFDebertaVaModel,
			)





class       _lowerCAmelCase   :




				def __init__(   self							,							_UpperCamelCase							,							_UpperCamelCase=13							,							_UpperCamelCase=7							,							_UpperCamelCase=True							,							_UpperCamelCase=True							,							_UpperCamelCase=True							,							_UpperCamelCase=True							,							_UpperCamelCase=99							,							_UpperCamelCase=32							,							_UpperCamelCase=2							,							_UpperCamelCase=4							,							_UpperCamelCase=37							,							_UpperCamelCase="gelu"							,							_UpperCamelCase=0.1							,							_UpperCamelCase=0.1							,							_UpperCamelCase=512							,							_UpperCamelCase=16							,							_UpperCamelCase=2							,							_UpperCamelCase=0.02							,							_UpperCamelCase=False							,							_UpperCamelCase=True							,							_UpperCamelCase="None"							,							_UpperCamelCase=3							,							_UpperCamelCase=4							,							_UpperCamelCase=None							,							)							-> Tuple:
							lowerCAmelCase_         =      parent
							lowerCAmelCase_         =      batch_size
							lowerCAmelCase_         =      seq_length
							lowerCAmelCase_         =      is_training
							lowerCAmelCase_         =      use_input_mask
							lowerCAmelCase_         =      use_token_type_ids
							lowerCAmelCase_         =      use_labels
							lowerCAmelCase_         =      vocab_size
							lowerCAmelCase_         =      hidden_size
							lowerCAmelCase_         =      num_hidden_layers
							lowerCAmelCase_         =      num_attention_heads
							lowerCAmelCase_         =      intermediate_size
							lowerCAmelCase_         =      hidden_act
							lowerCAmelCase_         =      hidden_dropout_prob
							lowerCAmelCase_         =      attention_probs_dropout_prob
							lowerCAmelCase_         =      max_position_embeddings
							lowerCAmelCase_         =      type_vocab_size
							lowerCAmelCase_         =      type_sequence_label_size
							lowerCAmelCase_         =      initializer_range
							lowerCAmelCase_         =      num_labels
							lowerCAmelCase_         =      num_choices
							lowerCAmelCase_         =      relative_attention
							lowerCAmelCase_         =      position_biased_input
							lowerCAmelCase_         =      pos_att_type
							lowerCAmelCase_         =      scope




				def 	__a		(   self	)							-> List[str]:
							lowerCAmelCase_         =      ids_tensor([self.batch_size, self.seq_length]							,							self.vocab_size	)

							lowerCAmelCase_         =      None
							if self.use_input_mask:
										lowerCAmelCase_         =      random_attention_mask([self.batch_size, self.seq_length]	)

							lowerCAmelCase_         =      None
							if self.use_token_type_ids:
										lowerCAmelCase_         =      ids_tensor([self.batch_size, self.seq_length]							,							self.type_vocab_size	)

							lowerCAmelCase_         =      None
							lowerCAmelCase_         =      None
							lowerCAmelCase_         =      None
							if self.use_labels:
										lowerCAmelCase_         =      ids_tensor([self.batch_size]							,							self.type_sequence_label_size	)
										lowerCAmelCase_         =      ids_tensor([self.batch_size, self.seq_length]							,							self.num_labels	)

							lowerCAmelCase_         =      DebertaVaConfig(
							    vocab_size=self.vocab_size							,							hidden_size=self.hidden_size							,							num_hidden_layers=self.num_hidden_layers							,							num_attention_heads=self.num_attention_heads							,							intermediate_size=self.intermediate_size							,							hidden_act=self.hidden_act							,							hidden_dropout_prob=self.hidden_dropout_prob							,							attention_probs_dropout_prob=self.attention_probs_dropout_prob							,							max_position_embeddings=self.max_position_embeddings							,							type_vocab_size=self.type_vocab_size							,							relative_attention=self.relative_attention							,							position_biased_input=self.position_biased_input							,							initializer_range=self.initializer_range							,							return_dict=_UpperCamelCase							,							)

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> Dict:
							lowerCAmelCase_         =      TFDebertaVaModel(config=_UpperCamelCase	)
							lowerCAmelCase_         =      {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

							lowerCAmelCase_         =      [input_ids, input_mask]
							lowerCAmelCase_         =      model(_UpperCamelCase	)

							lowerCAmelCase_         =      model(_UpperCamelCase	)

							self.parent.assertEqual(result.last_hidden_state.shape							,							(self.batch_size, self.seq_length, self.hidden_size)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> Any:
							lowerCAmelCase_         =      TFDebertaVaForMaskedLM(config=_UpperCamelCase	)
							lowerCAmelCase_         =      {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.seq_length, self.vocab_size)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> str:
							lowerCAmelCase_         =      self.num_labels
							lowerCAmelCase_         =      TFDebertaVaForSequenceClassification(config=_UpperCamelCase	)
							lowerCAmelCase_         =      {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.num_labels)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> int:
							lowerCAmelCase_         =      self.num_labels
							lowerCAmelCase_         =      TFDebertaVaForTokenClassification(config=_UpperCamelCase	)
							lowerCAmelCase_         =      {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.seq_length, self.num_labels)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> Dict:
							lowerCAmelCase_         =      TFDebertaVaForQuestionAnswering(config=_UpperCamelCase	)
							lowerCAmelCase_         =      {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.start_logits.shape							,							(self.batch_size, self.seq_length)	)
							self.parent.assertEqual(result.end_logits.shape							,							(self.batch_size, self.seq_length)	)




				def 	__a		(   self	)							-> Tuple:
							lowerCAmelCase_         =      self.prepare_config_and_inputs()
							(
							    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    (
							    lowerCAmelCase_
							)      ,    
							)         =      config_and_inputs
							lowerCAmelCase_         =      {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
							return config, inputs_dict





@require_tf
class       _lowerCAmelCase   (      __a   , __a   , unittest.TestCase			):
				_lowercase     						=(
				    (
				        TFDebertaVaModel,
				        TFDebertaVaForMaskedLM,
				        TFDebertaVaForQuestionAnswering,
				        TFDebertaVaForSequenceClassification,
				        TFDebertaVaForTokenClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				_lowercase     						=(
				    {
				        '''feature-extraction''': TFDebertaVaModel,
				        '''fill-mask''': TFDebertaVaForMaskedLM,
				        '''question-answering''': TFDebertaVaForQuestionAnswering,
				        '''text-classification''': TFDebertaVaForSequenceClassification,
				        '''token-classification''': TFDebertaVaForTokenClassification,
				        '''zero-shot''': TFDebertaVaForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)

				_lowercase     						=False
				_lowercase     						=False




				def 	__a		(   self	)							-> Optional[int]:
							lowerCAmelCase_         =      TFDebertaVaModelTester(self	)
							lowerCAmelCase_         =      ConfigTester(self							,							config_class=_UpperCamelCase							,							hidden_size=37	)




				def 	__a		(   self	)							-> str:
							self.config_tester.run_common_tests()




				def 	__a		(   self	)							-> int:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCamelCase	)




				def 	__a		(   self	)							-> List[Any]:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase	)




				def 	__a		(   self	)							-> List[str]:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*_UpperCamelCase	)




				def 	__a		(   self	)							-> List[Any]:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*_UpperCamelCase	)




				def 	__a		(   self	)							-> int:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase	)




				@slow
				def 	__a		(   self	)							-> Union[str, Any]:
							lowerCAmelCase_         =      TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge"	)
							self.assertIsNotNone(_UpperCamelCase	)





@require_tf
class       _lowerCAmelCase   (      unittest.TestCase			):




				@unittest.skip(reason="Model not available yet"	)
				def 	__a		(   self	)							-> List[str]:
							pass




				@slow
				def 	__a		(   self	)							-> Dict:
							lowerCAmelCase_         =      TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge"	)
							lowerCAmelCase_         =      tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]	)
							lowerCAmelCase_         =      tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
							lowerCAmelCase_         =      model(_UpperCamelCase							,							attention_mask=_UpperCamelCase	)[0]

							lowerCAmelCase_         =      tf.constant(
							    [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]	)
							tf.debugging.assert_near(output[:, 1:4, 1:4]							,							_UpperCamelCase							,							atol=1e-4	)



