



'''simple docstring'''




import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
							from PIL import Image

							from transformers import (
							    AutoProcessor,
							    BertTokenizerFast,
							    BlipImageProcessor,
							    GPTaTokenizer,
							    InstructBlipProcessor,
							    PreTrainedTokenizerFast,
							)

@require_vision
class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		int							     =		tempfile.mkdtemp()

								UpperCAmelCase     :		Any							     =		BlipImageProcessor()
								UpperCAmelCase     :		List[str]							     =		GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model"""    )
								UpperCAmelCase     :		Optional[Any]							     =		BertTokenizerFast.from_pretrained("""hf-internal-testing/tiny-random-bert"""    )

								UpperCAmelCase     :		Any							     =		InstructBlipProcessor(A		,		A		,		A    )

								processor.save_pretrained(self.tmpdirname    )





	def  _lowercase(  self		,		**A    )			->			Optional[int]:
								return AutoProcessor.from_pretrained(self.tmpdirname		,		**A    ).tokenizer





	def  _lowercase(  self		,		**A    )			->			Dict:
								return AutoProcessor.from_pretrained(self.tmpdirname		,		**A    ).image_processor





	def  _lowercase(  self		,		**A    )			->			Dict:
								return AutoProcessor.from_pretrained(self.tmpdirname		,		**A    ).qformer_tokenizer





	def  _lowercase(  self    )			->			List[str]:
								shutil.rmtree(self.tmpdirname    )





	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		Union[str, Any]							     =		[np.random.randint(255		,		size=(3, 30, 400)		,		dtype=np.uinta    )]

								UpperCAmelCase     :		Any							     =		[Image.fromarray(np.moveaxis(A		,		0		,		-1    )    ) for x in image_inputs]

								return image_inputs





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Any							     =		InstructBlipProcessor(
								    tokenizer=self.get_tokenizer()		,		image_processor=self.get_image_processor()		,		qformer_tokenizer=self.get_qformer_tokenizer()		,		)
								processor.save_pretrained(self.tmpdirname    )

								UpperCAmelCase     :		List[str]							     =		self.get_tokenizer(bos_token="""(BOS)"""		,		eos_token="""(EOS)"""    )
								UpperCAmelCase     :		Union[str, Any]							     =		self.get_image_processor(do_normalize=A		,		padding_value=1.0    )

								UpperCAmelCase     :		Union[str, Any]							     =		InstructBlipProcessor.from_pretrained(
								    self.tmpdirname		,		bos_token="""(BOS)"""		,		eos_token="""(EOS)"""		,		do_normalize=A		,		padding_value=1.0    )

								self.assertEqual(processor.tokenizer.get_vocab()		,		tokenizer_add_kwargs.get_vocab()    )
								self.assertIsInstance(processor.tokenizer		,		A    )

								self.assertEqual(processor.image_processor.to_json_string()		,		image_processor_add_kwargs.to_json_string()    )
								self.assertIsInstance(processor.image_processor		,		A    )
								self.assertIsInstance(processor.qformer_tokenizer		,		A    )





	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[Any]							     =		self.get_image_processor()
								UpperCAmelCase     :		List[Any]							     =		self.get_tokenizer()
								UpperCAmelCase     :		int							     =		self.get_qformer_tokenizer()

								UpperCAmelCase     :		List[str]							     =		InstructBlipProcessor(
								    tokenizer=A		,		image_processor=A		,		qformer_tokenizer=A    )

								UpperCAmelCase     :		int							     =		self.prepare_image_inputs()

								UpperCAmelCase     :		Any							     =		image_processor(A		,		return_tensors="""np"""    )
								UpperCAmelCase     :		Tuple							     =		processor(images=A		,		return_tensors="""np"""    )

								for key in input_feat_extract.keys():
															self.assertAlmostEqual(input_feat_extract[key].sum()		,		input_processor[key].sum()		,		delta=1e-2    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Optional[int]							     =		self.get_image_processor()
								UpperCAmelCase     :		int							     =		self.get_tokenizer()
								UpperCAmelCase     :		Dict							     =		self.get_qformer_tokenizer()

								UpperCAmelCase     :		Any							     =		InstructBlipProcessor(
								    tokenizer=A		,		image_processor=A		,		qformer_tokenizer=A    )

								UpperCAmelCase     :		List[Any]							     =		"""lower newer"""

								UpperCAmelCase     :		str							     =		processor(text=A    )

								UpperCAmelCase     :		List[str]							     =		tokenizer(A		,		return_token_type_ids=A    )
								UpperCAmelCase     :		int							     =		qformer_tokenizer(A		,		return_token_type_ids=A    )

								for key in encoded_tokens.keys():
															self.assertListEqual(encoded_tokens[key]		,		encoded_processor[key]    )

								for key in encoded_tokens_qformer.keys():
															self.assertListEqual(encoded_tokens_qformer[key]		,		encoded_processor["""qformer_""" + key]    )





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		str							     =		self.get_image_processor()
								UpperCAmelCase     :		Optional[Any]							     =		self.get_tokenizer()
								UpperCAmelCase     :		str							     =		self.get_qformer_tokenizer()

								UpperCAmelCase     :		List[str]							     =		InstructBlipProcessor(
								    tokenizer=A		,		image_processor=A		,		qformer_tokenizer=A    )

								UpperCAmelCase     :		List[Any]							     =		"""lower newer"""
								UpperCAmelCase     :		List[str]							     =		self.prepare_image_inputs()

								UpperCAmelCase     :		Union[str, Any]							     =		processor(text=A		,		images=A    )

								self.assertListEqual(
								    list(inputs.keys()    )		,		["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""]		,		)

								# test if it raises when no input is passed
								with pytest.raises(A    ):
															processor()





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     :		Optional[int]							     =		self.get_image_processor()
								UpperCAmelCase     :		List[Any]							     =		self.get_tokenizer()
								UpperCAmelCase     :		List[str]							     =		self.get_qformer_tokenizer()

								UpperCAmelCase     :		Optional[Any]							     =		InstructBlipProcessor(
								    tokenizer=A		,		image_processor=A		,		qformer_tokenizer=A    )

								UpperCAmelCase     :		List[Any]							     =		[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

								UpperCAmelCase     :		Tuple							     =		processor.batch_decode(A    )
								UpperCAmelCase     :		Tuple							     =		tokenizer.batch_decode(A    )

								self.assertListEqual(A		,		A    )






	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Union[str, Any]							     =		self.get_image_processor()
								UpperCAmelCase     :		Optional[int]							     =		self.get_tokenizer()
								UpperCAmelCase     :		List[Any]							     =		self.get_qformer_tokenizer()

								UpperCAmelCase     :		Union[str, Any]							     =		InstructBlipProcessor(
								    tokenizer=A		,		image_processor=A		,		qformer_tokenizer=A    )

								UpperCAmelCase     :		Dict							     =		"""lower newer"""
								UpperCAmelCase     :		Any							     =		self.prepare_image_inputs()

								UpperCAmelCase     :		Dict							     =		processor(text=A		,		images=A    )

								self.assertListEqual(
								    list(inputs.keys()    )		,		["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""]		,		)






'''simple docstring'''




from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

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


if is_tf_available():
							import tensorflow as tf

							from transformers import TFBlipTextModel
							from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST

class 			UpperCamelCase_ :





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





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		Optional[int]							     =		ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size    )

								UpperCAmelCase     :		Union[str, Any]							     =		None
								if self.use_input_mask:
															UpperCAmelCase     :		str							     =		random_attention_mask([self.batch_size, self.seq_length]    )

								if input_mask is not None:
															UpperCAmelCase     :		Tuple							     =		input_mask.numpy()
															UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		input_mask.shape
															UpperCAmelCase     :		Optional[int]							     =		np.random.randint(1		,		seq_length - 1		,		size=(batch_size,)    )
															for batch_idx, start_index in enumerate(A    ):
																						UpperCAmelCase     :		Tuple							     =		1
																						UpperCAmelCase     :		Optional[Any]							     =		0

								UpperCAmelCase     :		int							     =		self.get_config()

								return config, input_ids, tf.convert_to_tensor(A    )





	def  _lowercase(  self    )			->			int:
								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  _lowercase(  self		,		A		,		A		,		A    )			->			Union[str, Any]:
								UpperCAmelCase     :		int							     =		TFBlipTextModel(config=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		model(A		,		attention_mask=A		,		training=A    )
								UpperCAmelCase     :		int							     =		model(A		,		training=A    )
								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  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Dict							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		Any							     =		config_and_inputs
								UpperCAmelCase     :		Optional[Any]							     =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
								return config, inputs_dict




@require_tf
class 			UpperCamelCase_ (							__magic_name__      ,     unittest.TestCase			):
	lowercase          = (TFBlipTextModel,) if is_tf_available() else ()
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Union[str, Any]							     =		BlipTextModelTester(self    )
								UpperCAmelCase     :		List[str]							     =		ConfigTester(self		,		config_class=A		,		hidden_size=37    )





	def  _lowercase(  self    )			->			Tuple:
								self.config_tester.run_common_tests()





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		List[Any]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





	def  _lowercase(  self    )			->			List[str]:
								pass





	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""Blip does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Union[str, Any]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Dict:
								pass





	@slow
	def  _lowercase(  self    )			->			Dict:
								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		Any							     =		TFBlipTextModel.from_pretrained(A    )
															self.assertIsNotNone(A    )






	def  _lowercase(  self		,		A=True    )			->			str:
								super().test_pt_tf_model_equivalence(allow_missing_keys=A    )

