


"""simple docstring"""


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







		def  a_ (					self      :       int		)       ->						Optional[Any]:





						'''simple docstring'''







						_A					  =			self.config_class(**self.inputs_dict		)
						self.parent.assertTrue(hasattr(a__    ,   "tf_padding"		)		)
						self.parent.assertTrue(hasattr(a__    ,   "depth_multiplier"		)		)





class snake_case      :







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





						'''simple docstring'''







						_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      :       Any		)       ->						Tuple:





						'''simple docstring'''







						_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      :       Dict		)       ->						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  a_ (					self      :       Union[str, Any]    ,   a__      :       Union[str, Any]    ,   a__      :       Optional[int]    ,   a__      :       Union[str, Any]    ,   a__      :       Union[str, Any]		)       ->						str:





						'''simple docstring'''







						_A					  =			MobileNetVaModel(config=a__		)
						model.to(a__		)
						model.eval()
						_A					  =			model(a__		)
						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__      :       Any    ,   a__      :       List[str]    ,   a__      :       List[Any]    ,   a__      :       Any		)       ->						Optional[Any]:





						'''simple docstring'''







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







		def  a_ (					self      :       Optional[int]    ,   a__      :       int    ,   a__      :       str    ,   a__      :       Tuple    ,   a__      :       Tuple		)       ->						Optional[Any]:





						'''simple docstring'''







						_A					  =			self.num_labels
						_A					  =			MobileNetVaForSemanticSegmentation(a__		)
						model.to(a__		)
						model.eval()
						_A					  =			model(a__		)
						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(a__    ,   labels=a__		)
						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      :       str		)       ->						int:





						'''simple docstring'''







						_A					  =			self.prepare_config_and_inputs()
						_A  ,		_A  ,		_A  ,		_A					  =			config_and_inputs
						_A					  =			{"pixel_values": pixel_values}
						return config, inputs_dict





@require_torch
class snake_case      (  _UpperCamelCase     ,				_UpperCamelCase     ,				unittest.TestCase):
		__UpperCamelCase           =			(
		    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		__UpperCamelCase           =			(
		    {
		        'feature-extraction': MobileNetVaModel,
		        'image-classification': MobileNetVaForImageClassification,
		        'image-segmentation': MobileNetVaForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		__UpperCamelCase           =			False
		__UpperCamelCase           =			False
		__UpperCamelCase           =			False
		__UpperCamelCase           =			False







		def  a_ (					self      :       Optional[Any]		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			MobileNetVaModelTester(self		)
						_A					  =			MobileNetVaConfigTester(self    ,   config_class=a__    ,   has_text_modality=a__		)







		def  a_ (					self      :       List[Any]		)       ->						List[str]:





						'''simple docstring'''







						self.config_tester.run_common_tests()







		@unittest.skip(reason="MobileNetV2 does not use inputs_embeds"		)
		def  a_ (					self      :       Any		)       ->						Any:





						'''simple docstring'''







						pass







		@unittest.skip(reason="MobileNetV2 does not support input and output embeddings"		)
		def  a_ (					self      :       str		)       ->						str:





						'''simple docstring'''







						pass







		@unittest.skip(reason="MobileNetV2 does not output attentions"		)
		def  a_ (					self      :       int		)       ->						List[str]:





						'''simple docstring'''







						pass







		def  a_ (					self      :       Optional[int]		)       ->						List[str]:





						'''simple docstring'''







						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()

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







		def  a_ (					self      :       Union[str, Any]		)       ->						Tuple:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a__		)







		def  a_ (					self      :       List[str]		)       ->						str:





						'''simple docstring'''







						def check_hidden_states_output(a__      :       Optional[int]    ,   a__      :       List[str]    ,   a__      :       List[str]		):
										_A					  =			model_class(a__		)
										model.to(a__		)
										model.eval()

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

										_A					  =			outputs.hidden_states

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

						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()

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

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

										check_hidden_states_output(a__    ,   a__    ,   a__		)







		def  a_ (					self      :       Tuple		)       ->						Any:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*a__		)







		def  a_ (					self      :       Dict		)       ->						Dict:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*a__		)







		@slow
		def  a_ (					self      :       List[str]		)       ->						Any:





						'''simple docstring'''







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






def      a__ (				)	->	Union[str, Any]:
				_A					  =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
				return image




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







		@cached_property
		def  a_ (					self      :       Union[str, Any]		)       ->						str:





						'''simple docstring'''







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







		@slow
		def  a_ (					self      :       Union[str, Any]		)       ->						str:





						'''simple docstring'''







						_A					  =			MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"		).to(a__		)

						_A					  =			self.default_image_processor
						_A					  =			prepare_img()
						_A					  =			image_processor(images=a__    ,   return_tensors="pt"		).to(a__		)

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

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

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

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







		@slow
		def  a_ (					self      :       str		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"		)
						_A					  =			model.to(a__		)

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

						_A					  =			prepare_img()
						_A					  =			image_processor(images=a__    ,   return_tensors="pt"		).to(a__		)

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

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

						_A					  =			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=a__    ,   )

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



"""simple docstring"""


import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


a_       							=    logging.get_logger(__name__)
class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			['input_features']







		def __init__(					self      :       int    ,   a__      :       Optional[Any]=80    ,   a__      :       Optional[int]=1_60_00    ,   a__      :       int=1_60    ,   a__      :       Union[str, Any]=30    ,   a__      :       Tuple=4_00    ,   a__      :       List[Any]=0.0    ,   a__      :       Optional[Any]=False    ,   **a__      :       List[Any]    ,   )       ->						str:





						'''simple docstring'''







						super().__init__(
						    feature_size=a__    ,   sampling_rate=a__    ,   padding_value=a__    ,   return_attention_mask=a__    ,   **a__    ,   )
						_A					  =			n_fft
						_A					  =			hop_length
						_A					  =			chunk_length
						_A					  =			chunk_length * sampling_rate
						_A					  =			self.n_samples // hop_length
						_A					  =			sampling_rate
						_A					  =			mel_filter_bank(
						    num_frequency_bins=1 + n_fft // 2    ,   num_mel_filters=a__    ,   min_frequency=0.0    ,   max_frequency=8_0_0_0.0    ,   sampling_rate=a__    ,   norm="slaney"    ,   mel_scale="slaney"    ,   )







		def  a_ (					self      :       int    ,   a__      :       np.array		)       ->						np.ndarray:





						'''simple docstring'''







						_A					  =			spectrogram(
						    a__    ,   window_function(self.n_fft    ,   "hann"		)    ,   frame_length=self.n_fft    ,   hop_length=self.hop_length    ,   power=2.0    ,   mel_filters=self.mel_filters    ,   log_mel="log10"    ,   )
						_A					  =			log_spec[:, :-1]
						_A					  =			np.maximum(a__    ,   log_spec.max() - 8.0		)
						_A					  =			(log_spec + 4.0) / 4.0
						return log_spec







		@staticmethod
		# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
		def  a_ (					a__      :       List[np.ndarray]    ,   a__      :       List[np.ndarray]    ,   a__      :       float = 0.0		)       ->						List[np.ndarray]:





						'''simple docstring'''







						if attention_mask is not None:
										_A					  =			np.array(a__    ,   np.intaa		)
										_A					  =			[]

										for vector, length in zip(a__    ,   attention_mask.sum(-1		)		):
														_A					  =			(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7		)
														if length < normed_slice.shape[0]:
																		_A					  =			padding_value

														normed_input_values.append(a__		)
						else:
										_A					  =			[(x - x.mean()) / np.sqrt(x.var() + 1E-7		) for x in input_values]

						return normed_input_values







		def __call__(					self      :       Optional[int]    ,   a__      :       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]    ,   a__      :       bool = True    ,   a__      :       Optional[int] = None    ,   a__      :       Optional[Union[str, TensorType]] = None    ,   a__      :       Optional[bool] = None    ,   a__      :       Optional[str] = "max_length"    ,   a__      :       Optional[int] = None    ,   a__      :       Optional[int] = None    ,   a__      :       Optional[bool] = None    ,   **a__      :       Dict    ,   )       ->						BatchFeature:





						'''simple docstring'''







						if sampling_rate is not None:
										if sampling_rate != self.sampling_rate:
														raise ValueError(
														    F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
														    F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
														    F""" was sampled with {self.sampling_rate} and not {sampling_rate}."""		)
						else:
										logger.warning(
										    "It is strongly recommended to pass the `sampling_rate` argument to this function. "
										    "Failing to do so can result in silent errors that might be hard to debug."		)

						_A					  =			isinstance(a__    ,   np.ndarray		) and len(raw_speech.shape		) > 1
						if is_batched_numpy and len(raw_speech.shape		) > 2:
										raise ValueError(F"""Only mono-channel audio is supported for input to {self}"""		)
						_A					  =			is_batched_numpy or (
						    isinstance(a__    ,   (list, tuple)		) and (isinstance(raw_speech[0]    ,   (np.ndarray, tuple, list)		))
						)

						if is_batched:
										_A					  =			[np.asarray([speech]    ,   dtype=np.floataa		).T for speech in raw_speech]
						elif not is_batched and not isinstance(a__    ,   np.ndarray		):
										_A					  =			np.asarray(a__    ,   dtype=np.floataa		)
						elif isinstance(a__    ,   np.ndarray		) and raw_speech.dtype is np.dtype(np.floataa		):
										_A					  =			raw_speech.astype(np.floataa		)

						# always return batch
						if not is_batched:
										_A					  =			[np.asarray([raw_speech]		).T]

						_A					  =			BatchFeature({"input_features": raw_speech}		)

						# convert into correct format for padding

						_A					  =			self.pad(
						    a__    ,   padding=a__    ,   max_length=max_length if max_length else self.n_samples    ,   truncation=a__    ,   pad_to_multiple_of=a__    ,   return_attention_mask=return_attention_mask or do_normalize    ,   )

						# zero-mean and unit-variance normalization
						if do_normalize:
										_A					  =			self.zero_mean_unit_var_norm(
										    padded_inputs["input_features"]    ,   attention_mask=padded_inputs["attention_mask"]    ,   padding_value=self.padding_value    ,   )
										_A					  =			np.stack(padded_inputs["input_features"]    ,   axis=0		)

						# make sure list is in array format
						_A					  =			padded_inputs.get("input_features"		).transpose(2    ,   0    ,   1		)

						_A					  =			[self._np_extract_fbank_features(a__		) for waveform in input_features[0]]

						if isinstance(input_features[0]    ,   a__		):
										_A					  =			[np.asarray(a__    ,   dtype=np.floataa		) for feature in input_features]
						else:
										_A					  =			input_features

						if return_attention_mask:
										# rescale from sample (48000) to feature (3000)
										_A					  =			padded_inputs["attention_mask"][:, :: self.hop_length]

						if return_tensors is not None:
										_A					  =			padded_inputs.convert_to_tensors(a__		)

						return padded_inputs







		def  a_ (					self      :       Dict		)       ->						Dict[str, Any]:





						'''simple docstring'''







						_A					  =			copy.deepcopy(self.__dict__		)
						_A					  =			self.__class__.__name__
						if "mel_filters" in output:
										del output["mel_filters"]
						return output