




import inspect
import unittest

from transformers import MobileNetVaConfig
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 transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
			from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileNetVaImageProcessor







class a (     lowercase__  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.config_class(**self.inputs_dict				)
													self.parent.assertTrue(hasattr(UpperCAmelCase__				,							'''tf_padding'''				)				)
													self.parent.assertTrue(hasattr(UpperCAmelCase__				,							'''depth_multiplier'''				)				)







class a :
						"""simple docstring"""

						def __init__( self :     int				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     Union[str, Any]=13				,							lowerCamelCase__ :     Any=3				,							lowerCamelCase__ :     Union[str, Any]=32				,							lowerCamelCase__ :     Union[str, Any]=0.2_5				,							lowerCamelCase__ :     List[Any]=8				,							lowerCamelCase__ :     Union[str, Any]=8				,							lowerCamelCase__ :     str=6				,							lowerCamelCase__ :     int=32				,							lowerCamelCase__ :     Optional[Any]=True				,							lowerCamelCase__ :     Union[str, Any]=True				,							lowerCamelCase__ :     int=True				,							lowerCamelCase__ :     Optional[int]="relu6"				,							lowerCamelCase__ :     List[Any]=1_280				,							lowerCamelCase__ :     Union[str, Any]=0.1				,							lowerCamelCase__ :     Optional[Any]=0.0_2				,							lowerCamelCase__ :     str=True				,							lowerCamelCase__ :     List[str]=True				,							lowerCamelCase__ :     Union[str, Any]=10				,							lowerCamelCase__ :     Tuple=None				,							)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    parent
													__lowercase      =    batch_size
													__lowercase      =    num_channels
													__lowercase      =    image_size
													__lowercase      =    depth_multiplier
													__lowercase      =    depth_divisible_by
													__lowercase      =    min_depth
													__lowercase      =    expand_ratio
													__lowercase      =    tf_padding
													__lowercase      =    output_stride
													__lowercase      =    first_layer_is_expansion
													__lowercase      =    finegrained_output
													__lowercase      =    hidden_act
													__lowercase      =    last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier				)
													__lowercase      =    classifier_dropout_prob
													__lowercase      =    use_labels
													__lowercase      =    is_training
													__lowercase      =    num_labels
													__lowercase      =    initializer_range
													__lowercase      =    scope






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						str:
													"""simple docstring"""


													__lowercase      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

													__lowercase      =    self.get_config()

													return config, pixel_values, labels, pixel_labels






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Optional[Any]:
													"""simple docstring"""


													return MobileNetVaConfig(
													    num_channels=self.num_channels				,							image_size=self.image_size				,							depth_multiplier=self.depth_multiplier				,							depth_divisible_by=self.depth_divisible_by				,							min_depth=self.min_depth				,							expand_ratio=self.expand_ratio				,							output_stride=self.output_stride				,							first_layer_is_expansion=self.first_layer_is_expansion				,							finegrained_output=self.finegrained_output				,							hidden_act=self.hidden_act				,							tf_padding=self.tf_padding				,							classifier_dropout_prob=self.classifier_dropout_prob				,							initializer_range=self.initializer_range				,							)






						def     UpperCAmelCase_      ( self :     Tuple				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Dict				)    ->						str:
													"""simple docstring"""


													__lowercase      =    MobileNetVaModel(config=UpperCAmelCase__				)
													model.to(UpperCAmelCase__				)
													model.eval()
													__lowercase      =    model(UpperCAmelCase__				)
													self.parent.assertEqual(
													    result.last_hidden_state.shape				,							(
													        self.batch_size,
													        self.last_hidden_size,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)
													self.parent.assertEqual(
													    result.pooler_output.shape				,							(self.batch_size, self.last_hidden_size)				,							)






						def     UpperCAmelCase_      ( self :     Dict				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     Union[str, Any]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.num_labels
													__lowercase      =    MobileNetVaForImageClassification(UpperCAmelCase__				)
													model.to(UpperCAmelCase__				)
													model.eval()
													__lowercase      =    model(UpperCAmelCase__				,							labels=UpperCAmelCase__				)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)				)






						def     UpperCAmelCase_      ( self :     List[Any]				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     Any				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.num_labels
													__lowercase      =    MobileNetVaForSemanticSegmentation(UpperCAmelCase__				)
													model.to(UpperCAmelCase__				)
													model.eval()
													__lowercase      =    model(UpperCAmelCase__				)
													self.parent.assertEqual(
													    result.logits.shape				,							(
													        self.batch_size,
													        self.num_labels,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)
													__lowercase      =    model(UpperCAmelCase__				,							labels=UpperCAmelCase__				)
													self.parent.assertEqual(
													    result.logits.shape				,							(
													        self.batch_size,
													        self.num_labels,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.prepare_config_and_inputs()
													__lowercase      =    config_and_inputs
													__lowercase      =    {'''pixel_values''': pixel_values}
													return config, inputs_dict







@require_torch
class a (     lowercase__       ,						lowercase__       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       str       	=		(
						    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase_	:       Any       	=		(
						    {
						        'feature-extraction': MobileNetVaModel,
						        'image-classification': MobileNetVaForImageClassification,
						        'image-segmentation': MobileNetVaForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase_	:       Union[str, Any]       	=		False
						UpperCamelCase_	:       str       	=		False
						UpperCamelCase_	:       Tuple       	=		False
						UpperCamelCase_	:       List[str]       	=		False






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    MobileNetVaModelTester(self				)
													__lowercase      =    MobileNetVaConfigTester(self				,							config_class=UpperCAmelCase__				,							has_text_modality=UpperCAmelCase__				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Tuple:
													"""simple docstring"""


													self.config_tester.run_common_tests()






						@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''				)
						def     UpperCAmelCase_      ( self :     int				)    ->						Any:
													"""simple docstring"""


													pass






						@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''				)
						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						List[Any]:
													"""simple docstring"""


													pass






						@unittest.skip(reason='''MobileNetV2 does not output attentions'''				)
						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						int:
													"""simple docstring"""


													pass






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs_for_common()

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

																				__lowercase      =    ['''pixel_values''']
																				self.assertListEqual(arg_names[:1]				,							UpperCAmelCase__				)






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*UpperCAmelCase__				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						Any:
													"""simple docstring"""


													def check_hidden_states_output(lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     Dict				):
																				__lowercase      =    model_class(UpperCAmelCase__				)
																				model.to(UpperCAmelCase__				)
																				model.eval()

																				with torch.no_grad():
																											__lowercase      =    model(**self._prepare_for_class(UpperCAmelCase__				,							UpperCAmelCase__				)				)

																				__lowercase      =    outputs.hidden_states

																				__lowercase      =    16
																				self.assertEqual(len(UpperCAmelCase__				)				,							UpperCAmelCase__				)

													__lowercase      =    self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				__lowercase      =    True
																				check_hidden_states_output(UpperCAmelCase__				,							UpperCAmelCase__				,							UpperCAmelCase__				)

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

																				check_hidden_states_output(UpperCAmelCase__				,							UpperCAmelCase__				,							UpperCAmelCase__				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__				)






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase__				)






						@slow
						def     UpperCAmelCase_      ( self :     int				)    ->						Union[str, Any]:
													"""simple docstring"""


													for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__lowercase      =    MobileNetVaModel.from_pretrained(UpperCAmelCase__				)
																				self.assertIsNotNone(UpperCAmelCase__				)







def 		_A					(       )    -> Tuple:
							'''simple docstring'''


							__lowercase      =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
							return image







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

						@cached_property
						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						Tuple:
													"""simple docstring"""


													return (
													    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''				) if is_vision_available() else None
													)






						@slow
						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''				).to(UpperCAmelCase__				)

													__lowercase      =    self.default_image_processor
													__lowercase      =    prepare_img()
													__lowercase      =    image_processor(images=UpperCAmelCase__				,							return_tensors='''pt'''				).to(UpperCAmelCase__				)

													# forward pass
													with torch.no_grad():
																				__lowercase      =    model(**UpperCAmelCase__				)

													# verify the logits
													__lowercase      =    torch.Size((1, 1_001)				)
													self.assertEqual(outputs.logits.shape				,							UpperCAmelCase__				)

													__lowercase      =    torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]				).to(UpperCAmelCase__				)

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






						@slow
						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''				)
													__lowercase      =    model.to(UpperCAmelCase__				)

													__lowercase      =    MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''				)

													__lowercase      =    prepare_img()
													__lowercase      =    image_processor(images=UpperCAmelCase__				,							return_tensors='''pt'''				).to(UpperCAmelCase__				)

													# forward pass
													with torch.no_grad():
																				__lowercase      =    model(**UpperCAmelCase__				)
													__lowercase      =    outputs.logits

													# verify the logits
													__lowercase      =    torch.Size((1, 21, 65, 65)				)
													self.assertEqual(logits.shape				,							UpperCAmelCase__				)

													__lowercase      =    torch.tensor(
													    [
													        [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
													        [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
													        [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
													    ]				,							device=UpperCAmelCase__				,							)

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












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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast







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

						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    tempfile.mkdtemp()

													__lowercase      =    BlipImageProcessor()
													__lowercase      =    GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model'''				)

													__lowercase      =    BlipaProcessor(lowerCamelCase__				,							lowerCamelCase__				)

													processor.save_pretrained(self.tmpdirname				)






						def     UpperCAmelCase_      ( self :     Optional[int]				,							**lowerCamelCase__ :     Any				)    ->						str:
													"""simple docstring"""


													return AutoProcessor.from_pretrained(self.tmpdirname				,							**lowerCamelCase__				).tokenizer






						def     UpperCAmelCase_      ( self :     Dict				,							**lowerCamelCase__ :     List[str]				)    ->						Dict:
													"""simple docstring"""


													return AutoProcessor.from_pretrained(self.tmpdirname				,							**lowerCamelCase__				).image_processor






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						str:
													"""simple docstring"""


													shutil.rmtree(self.tmpdirname				)






						def     UpperCAmelCase_      ( self :     Any				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    [np.random.randint(255				,							size=(3, 30, 400)				,							dtype=np.uinta				)]

													__lowercase      =    [Image.fromarray(np.moveaxis(lowerCamelCase__				,							0				,							-1				)				) for x in image_inputs]

													return image_inputs






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						List[str]:
													"""simple docstring"""


													__lowercase      =    BlipaProcessor(tokenizer=self.get_tokenizer()				,							image_processor=self.get_image_processor()				)
													processor.save_pretrained(self.tmpdirname				)

													__lowercase      =    self.get_tokenizer(bos_token='''(BOS)'''				,							eos_token='''(EOS)'''				)
													__lowercase      =    self.get_image_processor(do_normalize=lowerCamelCase__				,							padding_value=1.0				)

													__lowercase      =    BlipaProcessor.from_pretrained(
													    self.tmpdirname				,							bos_token='''(BOS)'''				,							eos_token='''(EOS)'''				,							do_normalize=lowerCamelCase__				,							padding_value=1.0				)

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

													self.assertEqual(processor.image_processor.to_json_string()				,							image_processor_add_kwargs.to_json_string()				)
													self.assertIsInstance(processor.image_processor				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    image_processor(lowerCamelCase__				,							return_tensors='''np'''				)
													__lowercase      =    processor(images=lowerCamelCase__				,							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     UpperCAmelCase_      ( self :     Tuple				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''

													__lowercase      =    processor(text=lowerCamelCase__				)

													__lowercase      =    tokenizer(lowerCamelCase__				,							return_token_type_ids=lowerCamelCase__				)

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






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''
													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    processor(text=lowerCamelCase__				,							images=lowerCamelCase__				)

													self.assertListEqual(list(inputs.keys()				)				,							['''pixel_values''', '''input_ids''', '''attention_mask''']				)

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






						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

													__lowercase      =    processor.batch_decode(lowerCamelCase__				)
													__lowercase      =    tokenizer.batch_decode(lowerCamelCase__				)

													self.assertListEqual(lowerCamelCase__				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''
													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    processor(text=lowerCamelCase__				,							images=lowerCamelCase__				)

													# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
													self.assertListEqual(list(inputs.keys()				)				,							['''pixel_values''', '''input_ids''', '''attention_mask''']				)






