






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


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

lowerCAmelCase__    						=			'\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						(    __UpperCAmelCase       ):
						SCREAMING_SNAKE_CASE_:					Union[PIL.Image.Image, np.ndarray]







class _lowerCAmelCase						(    __UpperCAmelCase       ):







						def __init__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				)		->							Dict:
										super().__init__()

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







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

										_SCREAMING_SNAKE_CASE   :		List[str]       		=    latents * scheduler.init_noise_sigma
										return latents







						def 			A      (    self   ,				lowerCAmelCase_=0							)		->							Dict:
										if is_accelerate_available():
														from accelerate import cpu_offload
										else:
														raise ImportError('Please install accelerate via `pip install accelerate`'							)

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

										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    [self.image_encoder, self.prior]
										for cpu_offloaded_model in models:
														if cpu_offloaded_model is not None:
																		cpu_offload(lowerCAmelCase_   ,				lowerCAmelCase_							)







						@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(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 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				)		->							str:
										if isinstance(lowerCAmelCase_   ,				lowerCAmelCase_							) and isinstance(image[0]   ,				torch.Tensor							):
														_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    torch.cat(lowerCAmelCase_   ,				axis=0							) if image[0].ndim == 4 else torch.stack(lowerCAmelCase_   ,				axis=0							)

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

										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    image.to(dtype=self.image_encoder.dtype   ,				device=lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		Any       		=    self.image_encoder(lowerCAmelCase_							)['last_hidden_state']
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

										_SCREAMING_SNAKE_CASE   :		str       		=    image_embeds.repeat_interleave(lowerCAmelCase_   ,				dim=0							)

										if do_classifier_free_guidance:
														_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    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
														_SCREAMING_SNAKE_CASE   :		str       		=    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   ,				)		->							List[Any]:

										if isinstance(lowerCAmelCase_   ,				PIL.Image.Image							):
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    1
										elif isinstance(lowerCAmelCase_   ,				torch.Tensor							):
														_SCREAMING_SNAKE_CASE   :		Tuple       		=    image.shape[0]
										elif isinstance(lowerCAmelCase_   ,				lowerCAmelCase_							) and isinstance(image[0]   ,				(torch.Tensor, PIL.Image.Image)							):
														_SCREAMING_SNAKE_CASE   :		Dict       		=    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_							)}"""							)

										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    self._execution_device

										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    batch_size * num_images_per_prompt

										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    guidance_scale > 1.0
										_SCREAMING_SNAKE_CASE   :		int       		=    self._encode_image(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)

										# prior

										self.scheduler.set_timesteps(lowerCAmelCase_   ,				device=lowerCAmelCase_							)
										_SCREAMING_SNAKE_CASE   :		Any       		=    self.scheduler.timesteps

										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.prior.config.num_embeddings
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    self.prior.config.embedding_dim

										_SCREAMING_SNAKE_CASE   :		List[str]       		=    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
										_SCREAMING_SNAKE_CASE   :		str       		=    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
														_SCREAMING_SNAKE_CASE   :		Dict       		=    torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
														_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    self.scheduler.scale_model_input(lowerCAmelCase_   ,				lowerCAmelCase_							)

														_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    self.prior(
														    lowerCAmelCase_   ,				timestep=lowerCAmelCase_   ,				proj_embedding=lowerCAmelCase_   ,				).predicted_image_embedding

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

														_SCREAMING_SNAKE_CASE   :		Dict       		=    self.scheduler.step(
														    lowerCAmelCase_   ,				timestep=lowerCAmelCase_   ,				sample=lowerCAmelCase_   ,				).prev_sample

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

										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    []
										for i, latent in enumerate(lowerCAmelCase_							):
														print()
														_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    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_							)

										_SCREAMING_SNAKE_CASE   :		int       		=    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}"""							)

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

										if output_type == "pil":
														_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    [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"""
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
			import tensorflow as tf

			from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel


@require_tf
class _lowerCAmelCase						:
						SCREAMING_SNAKE_CASE_:					Union[str, Any] 					=				MBartConfig
						SCREAMING_SNAKE_CASE_:					Optional[Any] 					=				{}
						SCREAMING_SNAKE_CASE_:					Tuple 					=				'gelu'







						def __init__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_=1_3   ,				lowerCAmelCase_=7   ,				lowerCAmelCase_=True   ,				lowerCAmelCase_=False   ,				lowerCAmelCase_=9_9   ,				lowerCAmelCase_=3_2   ,				lowerCAmelCase_=2   ,				lowerCAmelCase_=4   ,				lowerCAmelCase_=3_7   ,				lowerCAmelCase_=0.1   ,				lowerCAmelCase_=0.1   ,				lowerCAmelCase_=2_0   ,				lowerCAmelCase_=2   ,				lowerCAmelCase_=1   ,				lowerCAmelCase_=0   ,				)		->							int:
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    parent
										_SCREAMING_SNAKE_CASE   :		str       		=    batch_size
										_SCREAMING_SNAKE_CASE   :		str       		=    seq_length
										_SCREAMING_SNAKE_CASE   :		Dict       		=    is_training
										_SCREAMING_SNAKE_CASE   :		int       		=    use_labels
										_SCREAMING_SNAKE_CASE   :		str       		=    vocab_size
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    hidden_size
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    num_hidden_layers
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    num_attention_heads
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    intermediate_size
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    hidden_dropout_prob
										_SCREAMING_SNAKE_CASE   :		int       		=    attention_probs_dropout_prob
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    max_position_embeddings
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    eos_token_id
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    pad_token_id
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    bos_token_id







						def 			A      (    self							)		->							Tuple:
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    ids_tensor([self.batch_size, self.seq_length - 1]   ,				self.vocab_size							)
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size							)   ,				1							)
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    tf.concat([input_ids, eos_tensor]   ,				axis=1							)

										_SCREAMING_SNAKE_CASE   :		Any       		=    ids_tensor([self.batch_size, self.seq_length]   ,				self.vocab_size							)

										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.config_cls(
										    vocab_size=self.vocab_size   ,				d_model=self.hidden_size   ,				encoder_layers=self.num_hidden_layers   ,				decoder_layers=self.num_hidden_layers   ,				encoder_attention_heads=self.num_attention_heads   ,				decoder_attention_heads=self.num_attention_heads   ,				encoder_ffn_dim=self.intermediate_size   ,				decoder_ffn_dim=self.intermediate_size   ,				dropout=self.hidden_dropout_prob   ,				attention_dropout=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				eos_token_ids=[2]   ,				bos_token_id=self.bos_token_id   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.pad_token_id   ,				**self.config_updates   ,				)
										_SCREAMING_SNAKE_CASE   :		Any       		=    prepare_mbart_inputs_dict(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)
										return config, inputs_dict







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							int:
										_SCREAMING_SNAKE_CASE   :		int       		=    TFMBartModel(config=lowerCAmelCase_							).get_decoder()
										_SCREAMING_SNAKE_CASE   :		int       		=    inputs_dict['input_ids']

										_SCREAMING_SNAKE_CASE   :		Tuple       		=    input_ids[:1, :]
										_SCREAMING_SNAKE_CASE   :		Any       		=    inputs_dict['attention_mask'][:1, :]
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    inputs_dict['head_mask']
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    1

										# first forward pass
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    model(lowerCAmelCase_   ,				attention_mask=lowerCAmelCase_   ,				head_mask=lowerCAmelCase_   ,				use_cache=lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		str       		=    outputs.to_tuple()
										_SCREAMING_SNAKE_CASE   :		str       		=    past_key_values[1]







def 				lowercase__		(					lowerCamelCase,						lowerCamelCase,						lowerCamelCase,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=None,						):
				if attention_mask is None:
								_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    tf.cast(tf.math.not_equal(lowerCamelCase,						config.pad_token_id       ),						tf.inta       )
				if decoder_attention_mask is None:
								_SCREAMING_SNAKE_CASE   :		Dict       		=    tf.concat(
								    [
								        tf.ones(decoder_input_ids[:, :1].shape,						dtype=tf.inta       ),
								        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],						config.pad_token_id       ),						tf.inta       ),
								    ],						axis=-1,						)
				if head_mask is None:
								_SCREAMING_SNAKE_CASE   :		Dict       		=    tf.ones((config.encoder_layers, config.encoder_attention_heads)       )
				if decoder_head_mask is None:
								_SCREAMING_SNAKE_CASE   :		int       		=    tf.ones((config.decoder_layers, config.decoder_attention_heads)       )
				if cross_attn_head_mask is None:
								_SCREAMING_SNAKE_CASE   :		int       		=    tf.ones((config.decoder_layers, config.decoder_attention_heads)       )
				return {
				    "input_ids": input_ids,
				    "decoder_input_ids": decoder_input_ids,
				    "attention_mask": attention_mask,
				    "decoder_attention_mask": decoder_attention_mask,
				    "head_mask": head_mask,
				    "decoder_head_mask": decoder_head_mask,
				    "cross_attn_head_mask": cross_attn_head_mask,
				}


@require_tf
class _lowerCAmelCase						(    __UpperCAmelCase   ,  __UpperCAmelCase   ,  unittest.TestCase       ):
						SCREAMING_SNAKE_CASE_:					List[str] 					=				(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
						SCREAMING_SNAKE_CASE_:					Dict 					=				(TFMBartForConditionalGeneration,) if is_tf_available() else ()
						SCREAMING_SNAKE_CASE_:					Tuple 					=				(
						    {
						        'conversational': TFMBartForConditionalGeneration,
						        'feature-extraction': TFMBartModel,
						        'summarization': TFMBartForConditionalGeneration,
						        'text2text-generation': TFMBartForConditionalGeneration,
						        'translation': TFMBartForConditionalGeneration,
						    }
						    if is_tf_available()
						    else {}
						)
						SCREAMING_SNAKE_CASE_:					Any 					=				True
						SCREAMING_SNAKE_CASE_:					int 					=				False
						SCREAMING_SNAKE_CASE_:					Optional[int] 					=				False







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							List[Any]:
										if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
														# Exception encountered when calling layer '...'
														return True

										return False







						def 			A      (    self							)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    TFMBartModelTester(self							)
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    ConfigTester(self   ,				config_class=lowerCAmelCase_							)







						def 			A      (    self							)		->							List[Any]:
										self.config_tester.run_common_tests()







						def 			A      (    self							)		->							Dict:
										_SCREAMING_SNAKE_CASE   :		Dict       		=    self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_							)







@require_sentencepiece
@require_tokenizers
@require_tf
class _lowerCAmelCase						(    unittest.TestCase       ):
						SCREAMING_SNAKE_CASE_:					str 					=				[
						    ' UN Chief Says There Is No Military Solution in Syria',
						]
						SCREAMING_SNAKE_CASE_:					Union[str, Any] 					=				[
						    'Şeful ONU declară că nu există o soluţie militară în Siria',
						]
						SCREAMING_SNAKE_CASE_:					Dict 					=				'facebook/mbart-large-en-ro'







						@cached_property
						def 			A      (    self							)		->							Union[str, Any]:
										return AutoTokenizer.from_pretrained(self.model_name							)







						@cached_property
						def 			A      (    self							)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name							)
										return model







						def 			A      (    self   ,				**lowerCAmelCase_							)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.translate_src_text(**lowerCAmelCase_							)
										self.assertListEqual(self.expected_text   ,				lowerCAmelCase_							)







						def 			A      (    self   ,				**lowerCAmelCase_							)		->							Tuple:
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.tokenizer(self.src_text   ,				**lowerCAmelCase_   ,				return_tensors='tf'							)
										_SCREAMING_SNAKE_CASE   :		int       		=    self.model.generate(
										    model_inputs.input_ids   ,				attention_mask=model_inputs.attention_mask   ,				num_beams=2							)
										_SCREAMING_SNAKE_CASE   :		int       		=    self.tokenizer.batch_decode(lowerCAmelCase_   ,				skip_special_tokens=lowerCAmelCase_							)
										return generated_words







						@slow
						def 			A      (    self							)		->							Any:
										self._assert_generated_batch_equal_expected()

