




import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import (
		    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
		    TimesformerForVideoClassification,
		    TimesformerModel,
		)
		from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from transformers import VideoMAEImageProcessor




class     snake_case__							:
				"""simple docstring"""



				def __init__(      self				:     List[Any]					,      __lowerCamelCase				:     str					,      __lowerCamelCase				:     Optional[Any]=13					,      __lowerCamelCase				:     Tuple=10					,      __lowerCamelCase				:     Optional[int]=3					,      __lowerCamelCase				:     List[Any]=2					,      __lowerCamelCase				:     List[Any]=2					,      __lowerCamelCase				:     Union[str, Any]=True					,      __lowerCamelCase				:     List[Any]=True					,      __lowerCamelCase				:     Union[str, Any]=32					,      __lowerCamelCase				:     Any=5					,      __lowerCamelCase				:     str=4					,      __lowerCamelCase				:     Optional[Any]=37					,      __lowerCamelCase				:     str="gelu"					,      __lowerCamelCase				:     List[Any]=0.1					,      __lowerCamelCase				:     List[Any]=0.1					,      __lowerCamelCase				:     Dict=10					,      __lowerCamelCase				:     Optional[int]=0.02					,      __lowerCamelCase				:     Optional[int]="divided_space_time"					,      __lowerCamelCase				:     Tuple=None					,      )					->     Optional[int]:
							a    =			parent
							a    =			batch_size
							a    =			image_size
							a    =			num_channels
							a    =			patch_size
							a    =			num_frames
							a    =			is_training
							a    =			use_labels
							a    =			hidden_size
							a    =			num_hidden_layers
							a    =			num_attention_heads
							a    =			intermediate_size
							a    =			hidden_act
							a    =			hidden_dropout_prob
							a    =			attention_probs_dropout_prob
							a    =			attention_type
							a    =			initializer_range
							a    =			scope
							a    =			num_labels

							# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
							a    =			(image_size // patch_size) ** 2
							a    =			(num_frames) * self.num_patches_per_frame + 1





				def 							__UpperCAmelCase							(      self				:     Dict							)					->     Dict:
							a    =			floats_tensor(
							    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

							a    =			None
							if self.use_labels:
										a    =			ids_tensor([self.batch_size]					,      self.num_labels							)

							a    =			self.get_config()

							return config, pixel_values, labels





				def 							__UpperCAmelCase							(      self				:     Any							)					->     List[str]:
							a    =			TimesformerConfig(
							    image_size=self.image_size					,      patch_size=self.patch_size					,      num_channels=self.num_channels					,      num_frames=self.num_frames					,      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					,      initializer_range=self.initializer_range					,      attention_type=self.attention_type					,      )
							a    =			self.num_labels
							return config





				def 							__UpperCAmelCase							(      self				:     Any					,      __lowerCamelCase				:     Dict					,      __lowerCamelCase				:     List[str]					,      __lowerCamelCase				:     Optional[Any]							)					->     Optional[Any]:
							a    =			TimesformerModel(config=__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a    =			model(__lowerCamelCase							)
							self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]					,      __lowerCamelCase				:     Optional[Any]					,      __lowerCamelCase				:     int					,      __lowerCamelCase				:     Dict							)					->     Tuple:
							a    =			TimesformerForVideoClassification(__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()

							a    =			model(__lowerCamelCase							)

							# verify the logits shape
							a    =			torch.Size((self.batch_size, self.num_labels)							)
							self.parent.assertEqual(result.logits.shape					,      __lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Union[str, Any]							)					->     Any:
							a    =			self.prepare_config_and_inputs()
							a    ,		a    ,		a    =			config_and_inputs
							a    =			{"pixel_values": pixel_values}
							return config, inputs_dict




@require_torch
class     snake_case__							(_UpperCamelCase    ,       _UpperCamelCase    ,       unittest.TestCase   ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_       :							str							 =					(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE_       :							str							 =					(
				    {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE_       :							Tuple							 =					False
				SCREAMING_SNAKE_CASE_       :							Union[str, Any]							 =					False
				SCREAMING_SNAKE_CASE_       :							Any							 =					False
				SCREAMING_SNAKE_CASE_       :							str							 =					False





				def 							__UpperCAmelCase							(      self				:     List[Any]							)					->     Any:
							a    =			TimesformerModelTester(self							)
							a    =			ConfigTester(
							    self					,      config_class=__lowerCamelCase					,      has_text_modality=__lowerCamelCase					,      hidden_size=37							)





				def 							__UpperCAmelCase							(      self				:     Any					,      __lowerCamelCase				:     Dict					,      __lowerCamelCase				:     Any					,      __lowerCamelCase				:     Any=False							)					->     Any:
							a    =			copy.deepcopy(__lowerCamelCase							)

							if return_labels:
										if model_class in get_values(__lowerCamelCase							):
													a    =			torch.zeros(
													    self.model_tester.batch_size					,      dtype=torch.long					,      device=__lowerCamelCase							)

							return inputs_dict





				def 							__UpperCAmelCase							(      self				:     Union[str, Any]							)					->     Dict:
							self.config_tester.run_common_tests()





				@unittest.skip(reason="TimeSformer does not use inputs_embeds"							)
				def 							__UpperCAmelCase							(      self				:     List[Any]							)					->     int:
							pass





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     Any:
							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a    =			model_class(__lowerCamelCase							)
										self.assertIsInstance(model.get_input_embeddings()					,      (nn.Module)							)
										a    =			model.get_output_embeddings()
										self.assertTrue(x is None or isinstance(__lowerCamelCase					,      nn.Linear							)							)





				def 							__UpperCAmelCase							(      self				:     int							)					->     Tuple:
							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a    =			model_class(__lowerCamelCase							)
										a    =			inspect.signature(model.forward							)
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										a    =			[*signature.parameters.keys()]

										a    =			["pixel_values"]
										self.assertListEqual(arg_names[:1]					,      __lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     List[str]							)					->     str:
							a    =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     Optional[Any]:
							a    =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase							)





				@slow
				def 							__UpperCAmelCase							(      self				:     int							)					->     List[str]:
							for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a    =			TimesformerModel.from_pretrained(__lowerCamelCase							)
										self.assertIsNotNone(__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Union[str, Any]							)					->     str:
							if not self.has_attentions:
										pass

							else:
										a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()
										a    =			True

										for model_class in self.all_model_classes:
													a    =			self.model_tester.seq_length
													a    =			self.model_tester.num_frames

													a    =			True
													a    =			False
													a    =			True
													a    =			model_class(__lowerCamelCase							)
													model.to(__lowerCamelCase							)
													model.eval()
													with torch.no_grad():
																a    =			model(**self._prepare_for_class(__lowerCamelCase					,      __lowerCamelCase							)							)
													a    =			outputs.attentions
													self.assertEqual(len(__lowerCamelCase							)					,      self.model_tester.num_hidden_layers							)

													# check that output_attentions also work using config
													del inputs_dict["output_attentions"]
													a    =			True
													a    =			model_class(__lowerCamelCase							)
													model.to(__lowerCamelCase							)
													model.eval()
													with torch.no_grad():
																a    =			model(**self._prepare_for_class(__lowerCamelCase					,      __lowerCamelCase							)							)
													a    =			outputs.attentions
													self.assertEqual(len(__lowerCamelCase							)					,      self.model_tester.num_hidden_layers							)

													# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
													self.assertListEqual(
													    list(attentions[0].shape[-3:]							)					,      [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,      )
													a    =			len(__lowerCamelCase							)

													# Check attention is always last and order is fine
													a    =			True
													a    =			True
													a    =			model_class(__lowerCamelCase							)
													model.to(__lowerCamelCase							)
													model.eval()
													with torch.no_grad():
																a    =			model(**self._prepare_for_class(__lowerCamelCase					,      __lowerCamelCase							)							)

													self.assertEqual(out_len + 1					,      len(__lowerCamelCase							)							)

													a    =			outputs.attentions

													self.assertEqual(len(__lowerCamelCase							)					,      self.model_tester.num_hidden_layers							)

													# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
													self.assertListEqual(
													    list(self_attentions[0].shape[-3:]							)					,      [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,      )





				def 							__UpperCAmelCase							(      self				:     List[Any]							)					->     Dict:
							def check_hidden_states_output(__lowerCamelCase				:     Dict					,      __lowerCamelCase				:     str					,      __lowerCamelCase				:     Any							):
										a    =			model_class(__lowerCamelCase							)
										model.to(__lowerCamelCase							)
										model.eval()

										with torch.no_grad():
													a    =			model(**self._prepare_for_class(__lowerCamelCase					,      __lowerCamelCase							)							)

										a    =			outputs.hidden_states
										a    =			self.model_tester.num_hidden_layers + 1
										self.assertEqual(len(__lowerCamelCase							)					,      __lowerCamelCase							)

										a    =			self.model_tester.seq_length

										self.assertListEqual(
										    list(hidden_states[0].shape[-2:]							)					,      [seq_length, self.model_tester.hidden_size]					,      )

							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a    =			True
										check_hidden_states_output(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase							)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										a    =			True

										check_hidden_states_output(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase							)




def 			__magic_name__				( ):






			'''simple docstring'''







			a    =			hf_hub_download(
			    repo_id="hf-internal-testing/spaghetti-video",  filename="eating_spaghetti.npy",  repo_type="dataset"   )
			a    =			np.load(A   )
			return list(A   )






@require_torch
@require_vision
class     snake_case__							(unittest.TestCase   ):
				"""simple docstring"""



				@cached_property
				def 							__UpperCAmelCase							(      self				:     List[str]							)					->     List[Any]:
							# logits were tested with a different mean and std, so we use the same here
							return (
							    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]					,      image_std=[0.5, 0.5, 0.5]							)
							    if is_vision_available()
							    else None
							)





				@slow
				def 							__UpperCAmelCase							(      self				:     int							)					->     List[Any]:
							a    =			TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400"							).to(
							    __lowerCamelCase							)

							a    =			self.default_image_processor
							a    =			prepare_video()
							a    =			image_processor(video[:8]					,      return_tensors="pt"							).to(__lowerCamelCase							)

							# forward pass
							with torch.no_grad():
										a    =			model(**__lowerCamelCase							)

							# verify the logits
							a    =			torch.Size((1, 4_00)							)
							self.assertEqual(outputs.logits.shape					,      __lowerCamelCase							)

							a    =			torch.tensor([-0.3_016, -0.7_713, -0.4_205]							).to(__lowerCamelCase							)

							self.assertTrue(torch.allclose(outputs.logits[0, :3]					,      __lowerCamelCase					,      atol=1e-4							)							)








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				='''
    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     _SCREAMING_SNAKE_CASE     (      snake_case_						):
	lowerCAmelCase__         = 42




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):



	def __init__(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  )				->       List[str]:
					super().__init__()

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



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase )				->       int:
					if latents is None:
									lowerCamelCase_						=			randn_tensor(lowercase						,  generator=lowercase						,  device=lowercase						,  dtype=lowercase )
					else:
									if latents.shape != shape:
													raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' )
									lowerCamelCase_						=			latents.to(lowercase )

					lowerCamelCase_						=			latents * scheduler.init_noise_sigma
					return latents



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase=0 )				->       int:
					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(lowercase						,  lowercase )



	@property
	def     SCREAMING_SNAKE_CASE_(    self )				->       List[str]:
					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(lowercase						,  "_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     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  )				->       List[str]:
					if isinstance(lowercase						,  lowercase ) and isinstance(image[0]						,  torch.Tensor ):
									lowerCamelCase_						=			torch.cat(lowercase						,  axis=0 ) if image[0].ndim == 4 else torch.stack(lowercase						,  axis=0 )

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

					lowerCamelCase_						=			image.to(dtype=self.image_encoder.dtype						,  device=lowercase )

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

					lowerCamelCase_						=			image_embeds.repeat_interleave(lowercase						,  dim=0 )

					if do_classifier_free_guidance:
									lowerCamelCase_						=			torch.zeros_like(lowercase )

									# 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(lowercase )
	def __call__(    self						,  lowercase						,  lowercase = 1						,  lowercase = 25						,  lowercase = None						,  lowercase = None						,  lowercase = 4.0						,  lowercase = 64						,  lowercase = "pil"						,  lowercase = True						,  )				->       Union[str, Any]:

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

					lowerCamelCase_						=			self._execution_device

					lowerCamelCase_						=			batch_size * num_images_per_prompt

					lowerCamelCase_						=			guidance_scale > 1.0
					lowerCamelCase_						=			self._encode_image(lowercase						,  lowercase						,  lowercase						,  lowercase )

					# prior

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

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

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

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

					lowerCamelCase_						=			[]
					for i, latent in enumerate(lowercase ):
									print()
									lowerCamelCase_						=			self.renderer.decode(
									    latent[None, :]						,  lowercase						,  size=lowercase						,  ray_batch_size=4096						,  n_coarse_samples=64						,  n_fine_samples=128						,  )

									images.append(lowercase )

					lowerCamelCase_						=			torch.stack(lowercase )

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


