

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask


if is_torch_available():
						import torch

						from transformers import BlipTextModel
						from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class     lowerCamelCase_   :




	def __init__( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase=12     ,     _UpperCAmelCase=7     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=99     ,     _UpperCAmelCase=32     ,     _UpperCAmelCase=32     ,     _UpperCAmelCase=5     ,     _UpperCAmelCase=4     ,     _UpperCAmelCase=37     ,     _UpperCAmelCase=0.1     ,     _UpperCAmelCase=0.1     ,     _UpperCAmelCase=512     ,     _UpperCAmelCase=0.0_2     ,     _UpperCAmelCase=0     ,     _UpperCAmelCase=None     ,     ):
			__UpperCAmelCase  :     List[Any]		=    parent
			__UpperCAmelCase  :     str		=    batch_size
			__UpperCAmelCase  :     Any		=    seq_length
			__UpperCAmelCase  :     int		=    is_training
			__UpperCAmelCase  :     List[Any]		=    use_input_mask
			__UpperCAmelCase  :     Any		=    use_labels
			__UpperCAmelCase  :     Any		=    vocab_size
			__UpperCAmelCase  :     Any		=    hidden_size
			__UpperCAmelCase  :     int		=    projection_dim
			__UpperCAmelCase  :     Dict		=    num_hidden_layers
			__UpperCAmelCase  :     Dict		=    num_attention_heads
			__UpperCAmelCase  :     List[Any]		=    intermediate_size
			__UpperCAmelCase  :     int		=    dropout
			__UpperCAmelCase  :     List[Any]		=    attention_dropout
			__UpperCAmelCase  :     Optional[int]		=    max_position_embeddings
			__UpperCAmelCase  :     List[str]		=    initializer_range
			__UpperCAmelCase  :     Optional[Any]		=    scope
			__UpperCAmelCase  :     Optional[Any]		=    bos_token_id




	def 						a					( self       ):
			__UpperCAmelCase  :     List[Any]		=    ids_tensor([self.batch_size, self.seq_length]     ,     self.vocab_size       )

			__UpperCAmelCase  :     Dict		=    None
			if self.use_input_mask:
					__UpperCAmelCase  :     Any		=    random_attention_mask([self.batch_size, self.seq_length]       )

			if input_mask is not None:
					__UpperCAmelCase, __UpperCAmelCase  :     List[str]		=    input_mask.shape
					__UpperCAmelCase  :     Optional[Any]		=    np.random.randint(1     ,     seq_length - 1     ,     size=(batch_size,)       )
					for batch_idx, start_index in enumerate(lowerCamelCase__       ):
							__UpperCAmelCase  :     Any		=    1
							__UpperCAmelCase  :     List[str]		=    0

			__UpperCAmelCase  :     int		=    self.get_config()

			return config, input_ids, input_mask




	def 						a					( self       ):
			return BlipTextConfig(
			    vocab_size=self.vocab_size     ,     hidden_size=self.hidden_size     ,     projection_dim=self.projection_dim     ,     num_hidden_layers=self.num_hidden_layers     ,     num_attention_heads=self.num_attention_heads     ,     intermediate_size=self.intermediate_size     ,     dropout=self.dropout     ,     attention_dropout=self.attention_dropout     ,     max_position_embeddings=self.max_position_embeddings     ,     initializer_range=self.initializer_range     ,     bos_token_id=self.bos_token_id     ,     )




	def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
			__UpperCAmelCase  :     Optional[Any]		=    BlipTextModel(config=lowerCamelCase__       )
			model.to(lowerCamelCase__       )
			model.eval()
			with torch.no_grad():
					__UpperCAmelCase  :     List[str]		=    model(lowerCamelCase__     ,     attention_mask=lowerCamelCase__       )
					__UpperCAmelCase  :     Dict		=    model(lowerCamelCase__       )
			self.parent.assertEqual(result.last_hidden_state.shape     ,     (self.batch_size, self.seq_length, self.hidden_size)       )
			self.parent.assertEqual(result.pooler_output.shape     ,     (self.batch_size, self.hidden_size)       )




	def 						a					( self       ):
			__UpperCAmelCase  :     Optional[int]		=    self.prepare_config_and_inputs()
			__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase  :     str		=    config_and_inputs
			__UpperCAmelCase  :     Union[str, Any]		=    {'input_ids': input_ids, 'attention_mask': input_mask}
			return config, inputs_dict



@require_torch
class     lowerCamelCase_   ( __UpperCAmelCase  ,							unittest.TestCase):
	_lowerCAmelCase       		=  (BlipTextModel,) if is_torch_available() else ()
	_lowerCAmelCase       		=  False
	_lowerCAmelCase       		=  False
	_lowerCAmelCase       		=  False




	def 						a					( self       ):
			__UpperCAmelCase  :     Dict		=    BlipTextModelTester(self       )
			__UpperCAmelCase  :     Any		=    ConfigTester(self     ,     config_class=lowerCamelCase__     ,     hidden_size=37       )




	def 						a					( self       ):
			self.config_tester.run_common_tests()




	def 						a					( self       ):
			__UpperCAmelCase  :     List[Any]		=    self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase__       )




	def 						a					( self       ):
			pass




	def 						a					( self       ):
			pass




	@unittest.skip(reason='Blip does not use inputs_embeds'       )
	def 						a					( self       ):
			pass




	@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
	def 						a					( self       ):
			pass




	@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
	def 						a					( self       ):
			pass




	@slow
	def 						a					( self       ):



			for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					__UpperCAmelCase  :     str		=    BlipTextModel.from_pretrained(lowerCamelCase__       )
					self.assertIsNotNone(lowerCamelCase__       )




	def 						a					( self       ):
			super().test_pt_tf_model_equivalence(allow_missing_keys=lowerCamelCase__       )








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


_SCREAMING_SNAKE_CASE          = False


@nightly
@require_torch_gpu
class     lowerCamelCase_   ( unittest.TestCase):




 def 						a					( self       ):
   # clean up the VRAM after each test
   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()




 def 						a					( self       ):
   __UpperCAmelCase  :     Dict		=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'       )
   # remove text_unet
   pipe.remove_unused_weights()
   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     Any		=    load_image(
       'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'       )

   __UpperCAmelCase  :     Optional[Any]		=    torch.manual_seed(0       )
   __UpperCAmelCase  :     Union[str, Any]		=    pipe(
       prompt='first prompt'     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=2     ,     output_type='numpy'     ,     ).images

   with tempfile.TemporaryDirectory() as tmpdirname:
     pipe.save_pretrained(_UpperCAmelCase       )
     __UpperCAmelCase  :     List[str]		=    VersatileDiffusionDualGuidedPipeline.from_pretrained(_UpperCAmelCase       )

   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     List[str]		=    generator.manual_seed(0       )
   __UpperCAmelCase  :     Optional[int]		=    pipe(
       prompt='first prompt'     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=2     ,     output_type='numpy'     ,     ).images

   assert np.abs(image - new_image       ).sum() < 1E-5, "Models don't have the same forward pass"




 def 						a					( self       ):
   __UpperCAmelCase  :     Optional[Any]		=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'       )
   pipe.remove_unused_weights()
   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     Tuple		=    'cyberpunk 2077'
   __UpperCAmelCase  :     Dict		=    load_image(
       'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'       )
   __UpperCAmelCase  :     Optional[Any]		=    torch.manual_seed(0       )
   __UpperCAmelCase  :     List[Any]		=    pipe(
       prompt=_UpperCAmelCase     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=50     ,     output_type='numpy'     ,     ).images

   __UpperCAmelCase  :     Tuple		=    image[0, 253:256, 253:256, -1]

   assert image.shape == (1, 512, 512, 3)
   __UpperCAmelCase  :     Tuple		=    np.array([0.0_7_8_7, 0.0_8_4_9, 0.0_8_2_6, 0.0_8_1_2, 0.0_8_0_7, 0.0_7_9_5, 0.0_8_1_8, 0.0_7_9_8, 0.0_7_7_9]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2





