






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     SCREAMING_SNAKE_CASE					(			snake_case       ):





							"""simple docstring"""

							def    __A			(	self: Any )     ->					Dict:
												_A										=			self.config_class(**self.inputs_dict )
												self.parent.assertTrue(hasattr(snake_case__		,  '''tf_padding''' ) )
												self.parent.assertTrue(hasattr(snake_case__		,  '''depth_multiplier''' ) )





class     SCREAMING_SNAKE_CASE					:





							"""simple docstring"""

							def __init__(	self: Union[str, Any]		,  __A: Any		,  __A: Optional[int]=13		,  __A: str=3		,  __A: str=32		,  __A: List[str]=0.25		,  __A: List[Any]=8		,  __A: List[str]=8		,  __A: Tuple=6		,  __A: List[str]=32		,  __A: List[str]=True		,  __A: Dict=True		,  __A: Tuple=True		,  __A: Union[str, Any]="relu6"		,  __A: Union[str, Any]=12_80		,  __A: Any=0.1		,  __A: Dict=0.02		,  __A: int=True		,  __A: List[str]=True		,  __A: Optional[Any]=10		,  __A: Tuple=None		,  )     ->					List[Any]:
												_A										=			parent
												_A										=			batch_size
												_A										=			num_channels
												_A										=			image_size
												_A										=			depth_multiplier
												_A										=			depth_divisible_by
												_A										=			min_depth
												_A										=			expand_ratio
												_A										=			tf_padding
												_A										=			output_stride
												_A										=			first_layer_is_expansion
												_A										=			finegrained_output
												_A										=			hidden_act
												_A										=			last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
												_A										=			classifier_dropout_prob
												_A										=			use_labels
												_A										=			is_training
												_A										=			num_labels
												_A										=			initializer_range
												_A										=			scope

							def    __A			(	self: List[str] )     ->					Any:
												_A										=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

												_A										=			self.get_config()

												return config, pixel_values, labels, pixel_labels

							def    __A			(	self: List[str] )     ->					int:
												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    __A			(	self: Optional[int]		,  __A: Tuple		,  __A: Optional[int]		,  __A: Any		,  __A: Dict )     ->					List[str]:
												_A										=			MobileNetVaModel(config=snake_case__ )
												model.to(snake_case__ )
												model.eval()
												_A										=			model(snake_case__ )
												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    __A			(	self: List[str]		,  __A: Optional[int]		,  __A: List[Any]		,  __A: Tuple		,  __A: Optional[int] )     ->					Tuple:
												_A										=			self.num_labels
												_A										=			MobileNetVaForImageClassification(snake_case__ )
												model.to(snake_case__ )
												model.eval()
												_A										=			model(snake_case__		,  labels=snake_case__ )
												self.parent.assertEqual(result.logits.shape		,  (self.batch_size, self.num_labels) )

							def    __A			(	self: Tuple		,  __A: List[str]		,  __A: List[str]		,  __A: Union[str, Any]		,  __A: str )     ->					List[str]:
												_A										=			self.num_labels
												_A										=			MobileNetVaForSemanticSegmentation(snake_case__ )
												model.to(snake_case__ )
												model.eval()
												_A										=			model(snake_case__ )
												self.parent.assertEqual(
												    result.logits.shape		,  (
												        self.batch_size,
												        self.num_labels,
												        self.image_size // self.output_stride,
												        self.image_size // self.output_stride,
												    )		,  )
												_A										=			model(snake_case__		,  labels=snake_case__ )
												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    __A			(	self: Any )     ->					List[Any]:
												_A										=			self.prepare_config_and_inputs()
												_A										=			config_and_inputs
												_A										=			{"pixel_values": pixel_values}
												return config, inputs_dict





@require_torch
class     SCREAMING_SNAKE_CASE					(			snake_case	,						snake_case	,						unittest.TestCase       ):





							"""simple docstring"""

							A_    	=       (
							    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							A_    	=       (
							    {
							        "feature-extraction": MobileNetVaModel,
							        "image-classification": MobileNetVaForImageClassification,
							        "image-segmentation": MobileNetVaForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							A_    	=       False
							A_    	=       False
							A_    	=       False
							A_    	=       False

							def    __A			(	self: Tuple )     ->					int:
												_A										=			MobileNetVaModelTester(self )
												_A										=			MobileNetVaConfigTester(self		,  config_class=snake_case__		,  has_text_modality=snake_case__ )

							def    __A			(	self: List[str] )     ->					Optional[int]:
												self.config_tester.run_common_tests()

							@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds''' )
							def    __A			(	self: Optional[Any] )     ->					Optional[Any]:
												pass

							@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings''' )
							def    __A			(	self: Any )     ->					Tuple:
												pass

							@unittest.skip(reason='''MobileNetV2 does not output attentions''' )
							def    __A			(	self: int )     ->					str:
												pass

							def    __A			(	self: List[str] )     ->					Any:
												_A										=			self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A										=			model_class(snake_case__ )
																	_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]		,  snake_case__ )

							def    __A			(	self: str )     ->					Union[str, Any]:
												_A										=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*snake_case__ )

							def    __A			(	self: Tuple )     ->					List[str]:




												def check_hidden_states_output(__A: List[Any]		,  __A: List[Any]		,  __A: int ):
																	_A										=			model_class(snake_case__ )
																	model.to(snake_case__ )
																	model.eval()

																	with torch.no_grad():
																						_A										=			model(**self._prepare_for_class(snake_case__		,  snake_case__ ) )

																	_A										=			outputs.hidden_states

																	_A										=			16
																	self.assertEqual(len(snake_case__ )		,  snake_case__ )

												_A										=			self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A										=			True
																	check_hidden_states_output(snake_case__		,  snake_case__		,  snake_case__ )

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

																	check_hidden_states_output(snake_case__		,  snake_case__		,  snake_case__ )

							def    __A			(	self: int )     ->					Dict:
												_A										=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*snake_case__ )

							def    __A			(	self: Optional[Any] )     ->					Tuple:
												_A										=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ )



							@slow
							def    __A			(	self: Optional[int] )     ->					Optional[int]:




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




def   __A       (  ):

					'''simple docstring'''







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





@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE					(			unittest.TestCase       ):





							"""simple docstring"""

							@cached_property
							def    __A			(	self: Union[str, Any] )     ->					int:
												return (
												    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224''' ) if is_vision_available() else None
												)

							@slow
							def    __A			(	self: List[Any] )     ->					int:
												_A										=			MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(snake_case__ )

												_A										=			self.default_image_processor
												_A										=			prepare_img()
												_A										=			image_processor(images=snake_case__		,  return_tensors='''pt''' ).to(snake_case__ )

												# forward pass
												with torch.no_grad():
																	_A										=			model(**snake_case__ )

												# verify the logits
												_A										=			torch.Size((1, 10_01) )
												self.assertEqual(outputs.logits.shape		,  snake_case__ )

												_A										=			torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(snake_case__ )

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



							@slow
							def    __A			(	self: Optional[Any] )     ->					Optional[Any]:
												_A										=			MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )
												_A										=			model.to(snake_case__ )

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

												_A										=			prepare_img()
												_A										=			image_processor(images=snake_case__		,  return_tensors='''pt''' ).to(snake_case__ )

												# forward pass
												with torch.no_grad():
																	_A										=			model(**snake_case__ )
												_A										=			outputs.logits

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

												_A										=			torch.tensor(
												    [
												        [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
												        [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
												        [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
												    ]		,  device=snake_case__		,  )

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





'''simple docstring'''





import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


SCREAMING_SNAKE_CASE     =       get_tests_dir("""fixtures""")
SCREAMING_SNAKE_CASE     =       get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
SCREAMING_SNAKE_CASE     =       get_tests_dir("""fixtures/dummy-config.json""")






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							0







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
   self.assertIsInstance(snake_case__			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							AutoFeatureExtractor.from_pretrained(snake_case__ )
   self.assertIsInstance(snake_case__			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   with tempfile.TemporaryDirectory() as tmpdirname:
     UpperCAmelCase__      :					Optional[Any]				       =							WavaVecaConfig()

     # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
     UpperCAmelCase__      :					Any				       =							AutoFeatureExtractor.from_pretrained(snake_case__ ).to_dict()

     config_dict.pop("feature_extractor_type" )
     UpperCAmelCase__      :					Union[str, Any]				       =							WavaVecaFeatureExtractor(**snake_case__ )

     # save in new folder
     model_config.save_pretrained(snake_case__ )
     config.save_pretrained(snake_case__ )

     UpperCAmelCase__      :					Tuple				       =							AutoFeatureExtractor.from_pretrained(snake_case__ )

     # make sure private variable is not incorrectly saved
     UpperCAmelCase__      :					List[Any]				       =							json.loads(config.to_json_string() )
     self.assertTrue("_processor_class" not in dict_as_saved )

   self.assertIsInstance(snake_case__			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							AutoFeatureExtractor.from_pretrained(snake_case__ )
   self.assertIsInstance(snake_case__			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   with self.assertRaisesRegex(
       snake_case__			,				"bert-base is not a local folder and is not a valid model identifier" ):
     UpperCAmelCase__      :					Optional[int]				       =							AutoFeatureExtractor.from_pretrained("bert-base" )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   with self.assertRaisesRegex(
       snake_case__			,				R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
     UpperCAmelCase__      :					List[str]				       =							AutoFeatureExtractor.from_pretrained(snake_case__			,				revision="aaaaaa" )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   with self.assertRaisesRegex(
       snake_case__			,				"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."			,				):
     UpperCAmelCase__      :					Optional[Any]				       =							AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   with self.assertRaises(snake_case__ ):
     UpperCAmelCase__      :					List[str]				       =							AutoFeatureExtractor.from_pretrained(
         "hf-internal-testing/test_dynamic_feature_extractor" )
   # If remote code is disabled, we can't load this config.
   with self.assertRaises(snake_case__ ):
     UpperCAmelCase__      :					Any				       =							AutoFeatureExtractor.from_pretrained(
         "hf-internal-testing/test_dynamic_feature_extractor"			,				trust_remote_code=snake_case__ )

   UpperCAmelCase__      :					Optional[Any]				       =							AutoFeatureExtractor.from_pretrained(
       "hf-internal-testing/test_dynamic_feature_extractor"			,				trust_remote_code=snake_case__ )
   self.assertEqual(feature_extractor.__class__.__name__			,				"NewFeatureExtractor" )

   # Test feature extractor can be reloaded.
   with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(snake_case__ )
     UpperCAmelCase__      :					Any				       =							AutoFeatureExtractor.from_pretrained(snake_case__			,				trust_remote_code=snake_case__ )
   self.assertEqual(reloaded_feature_extractor.__class__.__name__			,				"NewFeatureExtractor" )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   try:
     AutoConfig.register("custom"			,				snake_case__ )
     AutoFeatureExtractor.register(snake_case__			,				snake_case__ )
     # Trying to register something existing in the Transformers library will raise an error
     with self.assertRaises(snake_case__ ):
       AutoFeatureExtractor.register(snake_case__			,				snake_case__ )

     # Now that the config is registered, it can be used as any other config with the auto-API
     UpperCAmelCase__      :					str				       =							CustomFeatureExtractor.from_pretrained(snake_case__ )
     with tempfile.TemporaryDirectory() as tmp_dir:
       feature_extractor.save_pretrained(snake_case__ )
       UpperCAmelCase__      :					Optional[int]				       =							AutoFeatureExtractor.from_pretrained(snake_case__ )
       self.assertIsInstance(snake_case__			,				snake_case__ )

   finally:
     if "custom" in CONFIG_MAPPING._extra_content:
       del CONFIG_MAPPING._extra_content["custom"]
     if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
       del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   class 							UpperCAmelCase_							(    A				):

    '''simple docstring'''
    lowercase_					:    Optional[Any]				=							True

   try:
     AutoConfig.register("custom"			,				snake_case__ )
     AutoFeatureExtractor.register(snake_case__			,				snake_case__ )
     # If remote code is not set, the default is to use local
     UpperCAmelCase__      :					Any				       =							AutoFeatureExtractor.from_pretrained(
         "hf-internal-testing/test_dynamic_feature_extractor" )
     self.assertEqual(feature_extractor.__class__.__name__			,				"NewFeatureExtractor" )
     self.assertTrue(feature_extractor.is_local )

     # If remote code is disabled, we load the local one.
     UpperCAmelCase__      :					Optional[int]				       =							AutoFeatureExtractor.from_pretrained(
         "hf-internal-testing/test_dynamic_feature_extractor"			,				trust_remote_code=snake_case__ )
     self.assertEqual(feature_extractor.__class__.__name__			,				"NewFeatureExtractor" )
     self.assertTrue(feature_extractor.is_local )

     # If remote is enabled, we load from the Hub
     UpperCAmelCase__      :					int				       =							AutoFeatureExtractor.from_pretrained(
         "hf-internal-testing/test_dynamic_feature_extractor"			,				trust_remote_code=snake_case__ )
     self.assertEqual(feature_extractor.__class__.__name__			,				"NewFeatureExtractor" )
     self.assertTrue(not hasattr(snake_case__			,				"is_local" ) )

   finally:
     if "custom" in CONFIG_MAPPING._extra_content:
       del CONFIG_MAPPING._extra_content["custom"]
     if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
       del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]



