

'''simple docstring'''

import gc
import random
import unittest

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

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference





class 							_snake_case       (				__A		,     unittest.TestCase  ):
   _A				:   List[str]			      =    ShapEImgaImgPipeline
   _A				:   str			      =    ['image']
   _A				:   List[Any]			      =    ['image']
   _A				:   Optional[Any]			      =    [
       'num_images_per_prompt',
       'num_inference_steps',
       'generator',
       'latents',
       'guidance_scale',
       'frame_size',
       'output_type',
       'return_dict',
   ]
   _A				:   List[Any]			      =    False
   @property
   def 			__UpperCamelCase  (       self	:					Any							):
     return 32
   @property
   def 			__UpperCamelCase  (       self	:					Optional[int]							):
     return 32
   @property
   def 			__UpperCamelCase  (       self	:					int							):
     return self.time_input_dim * 4
   @property
   def 			__UpperCamelCase  (       self	:					str							):
     return 8
   @property
   def 			__UpperCamelCase  (       self	:					Any							):
     torch.manual_seed(0							)
     SCREAMING_SNAKE_CASE:Optional[Any]  					=    CLIPVisionConfig(
         hidden_size=self.text_embedder_hidden_size   ,image_size=64   ,projection_dim=self.text_embedder_hidden_size   ,intermediate_size=37   ,num_attention_heads=4   ,num_channels=3   ,num_hidden_layers=5   ,patch_size=1   ,)

     SCREAMING_SNAKE_CASE:Optional[Any]  					=    CLIPVisionModel(__UpperCAmelCase							)
     return model
   @property
   def 			__UpperCamelCase  (       self	:					int							):
     SCREAMING_SNAKE_CASE:int  					=    CLIPImageProcessor(
         crop_size=224   ,do_center_crop=__UpperCAmelCase   ,do_normalize=__UpperCAmelCase   ,do_resize=__UpperCAmelCase   ,image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]   ,image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]   ,resample=3   ,size=224   ,)

     return image_processor
   @property
   def 			__UpperCamelCase  (       self	:					List[Any]							):
     torch.manual_seed(0							)

     SCREAMING_SNAKE_CASE:List[Any]  					=    {
         "num_attention_heads": 2,
         "attention_head_dim": 16,
         "embedding_dim": self.time_input_dim,
         "num_embeddings": 32,
         "embedding_proj_dim": self.text_embedder_hidden_size,
         "time_embed_dim": self.time_embed_dim,
         "num_layers": 1,
         "clip_embed_dim": self.time_input_dim * 2,
         "additional_embeddings": 0,
         "time_embed_act_fn": "gelu",
         "norm_in_type": "layer",
         "embedding_proj_norm_type": "layer",
         "encoder_hid_proj_type": None,
         "added_emb_type": None,
     }

     SCREAMING_SNAKE_CASE:Union[str, Any]  					=    PriorTransformer(**__UpperCAmelCase							)
     return model
   @property
   def 			__UpperCamelCase  (       self	:					str							):
     torch.manual_seed(0							)

     SCREAMING_SNAKE_CASE:Optional[Any]  					=    {
         "param_shapes": (
             (self.renderer_dim, 93),
             (self.renderer_dim, 8),
             (self.renderer_dim, 8),
             (self.renderer_dim, 8),
         ),
         "d_latent": self.time_input_dim,
         "d_hidden": self.renderer_dim,
         "n_output": 12,
         "background": (
             0.1,
             0.1,
             0.1,
         ),
     }
     SCREAMING_SNAKE_CASE:List[str]  					=    ShapERenderer(**__UpperCAmelCase							)
     return model
   def 			__UpperCamelCase  (       self	:					Optional[Any]							):
     SCREAMING_SNAKE_CASE:Any  					=    self.dummy_prior
     SCREAMING_SNAKE_CASE:Union[str, Any]  					=    self.dummy_image_encoder
     SCREAMING_SNAKE_CASE:List[Any]  					=    self.dummy_image_processor
     SCREAMING_SNAKE_CASE:Any  					=    self.dummy_renderer

     SCREAMING_SNAKE_CASE:Dict  					=    HeunDiscreteScheduler(
         beta_schedule="exp"   ,num_train_timesteps=1_024   ,prediction_type="sample"   ,use_karras_sigmas=__UpperCAmelCase   ,clip_sample=__UpperCAmelCase   ,clip_sample_range=1.0   ,)
     SCREAMING_SNAKE_CASE:Tuple  					=    {
         "prior": prior,
         "image_encoder": image_encoder,
         "image_processor": image_processor,
         "renderer": renderer,
         "scheduler": scheduler,
     }

     return components
   def 			__UpperCamelCase  (       self	:					Dict   ,SCREAMING_SNAKE_CASE__	:					Any   ,SCREAMING_SNAKE_CASE__	:					Optional[int]=0							):
     SCREAMING_SNAKE_CASE:List[str]  					=    floats_tensor((1, 3, 64, 64)   ,rng=random.Random(__UpperCAmelCase							)							).to(__UpperCAmelCase							)

     if str(__UpperCAmelCase							).startswith("mps"							):
       SCREAMING_SNAKE_CASE:Dict  					=    torch.manual_seed(__UpperCAmelCase							)
     else:
       SCREAMING_SNAKE_CASE:int  					=    torch.Generator(device=__UpperCAmelCase							).manual_seed(__UpperCAmelCase							)
     SCREAMING_SNAKE_CASE:List[str]  					=    {
         "image": input_image,
         "generator": generator,
         "num_inference_steps": 1,
         "frame_size": 32,
         "output_type": "np",
     }
     return inputs
   def 			__UpperCamelCase  (       self	:					str							):
     SCREAMING_SNAKE_CASE:List[Any]  					=    "cpu"

     SCREAMING_SNAKE_CASE:Tuple  					=    self.get_dummy_components()

     SCREAMING_SNAKE_CASE:Optional[Any]  					=    self.pipeline_class(**__UpperCAmelCase							)
     SCREAMING_SNAKE_CASE:Union[str, Any]  					=    pipe.to(__UpperCAmelCase							)

     pipe.set_progress_bar_config(disable=__UpperCAmelCase							)

     SCREAMING_SNAKE_CASE:Tuple  					=    pipe(**self.get_dummy_inputs(__UpperCAmelCase							)							)
     SCREAMING_SNAKE_CASE:Any  					=    output.images[0]
     SCREAMING_SNAKE_CASE:str  					=    image[0, -3:, -3:, -1]

     assert image.shape == (20, 32, 32, 3)

     SCREAMING_SNAKE_CASE:Optional[Any]  					=    np.array(
         [
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
             0.00_039_216,
         ]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
   def 			__UpperCamelCase  (       self	:					List[str]							):
     # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
     self._test_inference_batch_consistent(batch_sizes=[1, 2]							)
   def 			__UpperCamelCase  (       self	:					Optional[Any]							):
     SCREAMING_SNAKE_CASE:Optional[int]  					=    torch_device == "cpu"
     SCREAMING_SNAKE_CASE:Dict  					=    True
     self._test_inference_batch_single_identical(
         batch_size=2   ,test_max_difference=__UpperCAmelCase   ,relax_max_difference=__UpperCAmelCase   ,)







   def 			__UpperCamelCase  (       self	:					int							):
     SCREAMING_SNAKE_CASE:Optional[Any]  					=    self.get_dummy_components()
     SCREAMING_SNAKE_CASE:List[str]  					=    self.pipeline_class(**__UpperCAmelCase							)
     SCREAMING_SNAKE_CASE:List[str]  					=    pipe.to(__UpperCAmelCase							)
     pipe.set_progress_bar_config(disable=__UpperCAmelCase							)

     SCREAMING_SNAKE_CASE:Tuple  					=    1
     SCREAMING_SNAKE_CASE:int  					=    2

     SCREAMING_SNAKE_CASE:Dict  					=    self.get_dummy_inputs(__UpperCAmelCase							)

     for key in inputs.keys():
       if key in self.batch_params:
         SCREAMING_SNAKE_CASE:List[str]  					=    batch_size * [inputs[key]]

     SCREAMING_SNAKE_CASE:Dict  					=    pipe(**__UpperCAmelCase   ,num_images_per_prompt=__UpperCAmelCase							)[0]

     assert images.shape[0] == batch_size * num_images_per_prompt





@slow
@require_torch_gpu
class 							_snake_case       (				unittest.TestCase  ):
   def 			__UpperCamelCase  (       self	:					List[str]							):
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()







   def 			__UpperCamelCase  (       self	:					int							):
     SCREAMING_SNAKE_CASE:List[str]  					=    load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png"							)
     SCREAMING_SNAKE_CASE:Any  					=    load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/shap_e/test_shap_e_img2img_out.npy"							)
     SCREAMING_SNAKE_CASE:Dict  					=    ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img"							)
     SCREAMING_SNAKE_CASE:Any  					=    pipe.to(__UpperCAmelCase							)
     pipe.set_progress_bar_config(disable=__UpperCAmelCase							)

     SCREAMING_SNAKE_CASE:Tuple  					=    torch.Generator(device=__UpperCAmelCase							).manual_seed(0							)

     SCREAMING_SNAKE_CASE:List[Any]  					=    pipe(
         __UpperCAmelCase   ,generator=__UpperCAmelCase   ,guidance_scale=3.0   ,num_inference_steps=64   ,frame_size=64   ,output_type="np"   ,).images[0]

     assert images.shape == (20, 64, 64, 3)

     assert_mean_pixel_difference(__UpperCAmelCase   ,__UpperCAmelCase							)







"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import 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 numpy
				import tensorflow as tf

				from transformers import (
				    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    BertConfig,
				    DPRConfig,
				    TFDPRContextEncoder,
				    TFDPRQuestionEncoder,
				    TFDPRReader,
				)
class 			UpperCamelCase__:





						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=5_12						,__UpperCAmelCase=16						,__UpperCAmelCase=2						,__UpperCAmelCase=0.0_2						,__UpperCAmelCase=3						,__UpperCAmelCase=4						,__UpperCAmelCase=None						,__UpperCAmelCase=0						,)    -> Dict:
													A__		   =							parent
													A__		   =							batch_size
													A__		   =							seq_length
													A__		   =							is_training
													A__		   =							use_input_mask
													A__		   =							use_token_type_ids
													A__		   =							use_labels
													A__		   =							vocab_size
													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__		   =							max_position_embeddings
													A__		   =							type_vocab_size
													A__		   =							type_sequence_label_size
													A__		   =							initializer_range
													A__		   =							num_labels
													A__		   =							num_choices
													A__		   =							scope
													A__		   =							projection_dim





						def  snake_case__		(				self   )    -> Optional[Any]:
													A__		   =							ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size   )

													A__		   =							None
													if self.use_input_mask:
																				# follow test_modeling_tf_ctrl.py
																				A__		   =							random_attention_mask([self.batch_size, self.seq_length]   )

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

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

													A__		   =							BertConfig(
													    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						,is_decoder=__UpperCAmelCase						,initializer_range=self.initializer_range						,)
													A__		   =							DPRConfig(projection_dim=self.projection_dim						,**config.to_dict()   )

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





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )    -> Tuple:
													A__		   =							TFDPRContextEncoder(config=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase						,attention_mask=__UpperCAmelCase						,token_type_ids=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase						,token_type_ids=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase   )
													self.parent.assertEqual(result.pooler_output.shape						,(self.batch_size, self.projection_dim or self.hidden_size)   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )    -> Union[str, Any]:
													A__		   =							TFDPRQuestionEncoder(config=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase						,attention_mask=__UpperCAmelCase						,token_type_ids=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase						,token_type_ids=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase   )
													self.parent.assertEqual(result.pooler_output.shape						,(self.batch_size, self.projection_dim or self.hidden_size)   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )    -> Optional[int]:
													A__		   =							TFDPRReader(config=__UpperCAmelCase   )
													A__		   =							model(__UpperCAmelCase						,attention_mask=__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)   )
													self.parent.assertEqual(result.relevance_logits.shape						,(self.batch_size,)   )





						def  snake_case__		(				self   )    -> int:
													A__		   =							self.prepare_config_and_inputs()
													(
													    (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     (
													    A__
													)   ,     
													)		   =							config_and_inputs
													A__		   =							{'input_ids': input_ids}
													return config, inputs_dict






@require_tf
class 			UpperCamelCase__(	__A						,  __A						,  unittest.TestCase       ):
						lowerCAmelCase__     :  Optional[int]  							=						(
						    (
						        TFDPRContextEncoder,
						        TFDPRQuestionEncoder,
						        TFDPRReader,
						    )
						    if is_tf_available()
						    else ()
						)
						lowerCAmelCase__     :  List[str]  							=						{'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

						lowerCAmelCase__     :  Tuple  							=						False
						lowerCAmelCase__     :  Optional[int]  							=						False
						lowerCAmelCase__     :  List[str]  							=						False
						lowerCAmelCase__     :  int  							=						False
						lowerCAmelCase__     :  str  							=						False





						def  snake_case__		(				self   )    -> str:
													A__		   =							TFDPRModelTester(self   )
													A__		   =							ConfigTester(self						,config_class=__UpperCAmelCase						,hidden_size=37   )





						def  snake_case__		(				self   )    -> Optional[Any]:
													self.config_tester.run_common_tests()





						def  snake_case__		(				self   )    -> int:
													A__		   =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_dpr_context_encoder(*__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> Optional[Any]:
													A__		   =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_dpr_question_encoder(*__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> List[str]:
													A__		   =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_dpr_reader(*__UpperCAmelCase   )





						@slow
						def  snake_case__		(				self   )    -> int:
													for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__		   =							TFDPRContextEncoder.from_pretrained(__UpperCAmelCase   )
																				self.assertIsNotNone(__UpperCAmelCase   )

													for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__		   =							TFDPRContextEncoder.from_pretrained(__UpperCAmelCase   )
																				self.assertIsNotNone(__UpperCAmelCase   )

													for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__		   =							TFDPRQuestionEncoder.from_pretrained(__UpperCAmelCase   )
																				self.assertIsNotNone(__UpperCAmelCase   )

													for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__		   =							TFDPRReader.from_pretrained(__UpperCAmelCase   )
																				self.assertIsNotNone(__UpperCAmelCase   )






@require_tf
class 			UpperCamelCase__(	unittest.TestCase       ):





						@slow
						def  snake_case__		(				self   )    -> Optional[Any]:
													A__		   =							TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'   )

													A__		   =							tf.constant(
													    [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]]   )  # [CLS] hello, is my dog cute? [SEP]
													A__		   =							model(__UpperCAmelCase   )[0]  # embedding shape = (1, 768)
													# compare the actual values for a slice.
													A__		   =							tf.constant(
													    [
													        [
													            0.0_3_2_3_6_2_5_3,
													            0.1_2_7_5_3_3_3_5,
													            0.1_6_8_1_8_5_0_9,
													            0.0_0_2_7_9_7_8_6,
													            0.3_8_9_6_9_3_3,
													            0.2_4_2_6_4_9_4_5,
													            0.2_1_7_8_9_7_1,
													            -0.0_2_3_3_5_2_2_7,
													            -0.0_8_4_8_1_9_5_9,
													            -0.1_4_3_2_4_1_1_7,
													        ]
													    ]   )
													self.assertTrue(numpy.allclose(output[:, :10].numpy()						,expected_slice.numpy()						,atol=1e-4   )   )





