
"""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, MobileNetVaModel
					from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import MobileNetVaImageProcessor

class 					__a     ( __a       ):



							'''simple docstring'''







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




										'''simple docstring'''
										__lowercase       =       self.config_class(**self.inputs_dict       )
										self.parent.assertTrue(hasattr(_lowerCamelCase  ,    "tf_padding"       )       )
										self.parent.assertTrue(hasattr(_lowerCamelCase  ,    "depth_multiplier"       )       )





class 					__a     :



							'''simple docstring'''







							def __init__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase=13  ,    _lowerCamelCase=3  ,    _lowerCamelCase=32  ,    _lowerCamelCase=0.25  ,    _lowerCamelCase=8  ,    _lowerCamelCase=True  ,    _lowerCamelCase=1_024  ,    _lowerCamelCase=32  ,    _lowerCamelCase="relu6"  ,    _lowerCamelCase=0.1  ,    _lowerCamelCase=0.02  ,    _lowerCamelCase=True  ,    _lowerCamelCase=True  ,    _lowerCamelCase=10  ,    _lowerCamelCase=None  ,    )			->							Optional[int]:




										'''simple docstring'''
										__lowercase       =       parent
										__lowercase       =       batch_size
										__lowercase       =       num_channels
										__lowercase       =       image_size
										__lowercase       =       depth_multiplier
										__lowercase       =       min_depth
										__lowercase       =       tf_padding
										__lowercase       =       int(last_hidden_size * depth_multiplier       )
										__lowercase       =       output_stride
										__lowercase       =       hidden_act
										__lowercase       =       classifier_dropout_prob
										__lowercase       =       use_labels
										__lowercase       =       is_training
										__lowercase       =       num_labels
										__lowercase       =       initializer_range
										__lowercase       =       scope
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




										'''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   SCREAMING_SNAKE_CASE						(     self       )			->							List[str]:




										'''simple docstring'''
										return MobileNetVaConfig(
										    num_channels=self.num_channels  ,    image_size=self.image_size  ,    depth_multiplier=self.depth_multiplier  ,    min_depth=self.min_depth  ,    tf_padding=self.tf_padding  ,    hidden_act=self.hidden_act  ,    classifier_dropout_prob=self.classifier_dropout_prob  ,    initializer_range=self.initializer_range  ,    )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							Dict:




										'''simple docstring'''
										__lowercase       =       MobileNetVaModel(config=_lowerCamelCase       )
										model.to(_lowerCamelCase       )
										model.eval()
										__lowercase       =       model(_lowerCamelCase       )
										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,
										    )  ,    )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							str:




										'''simple docstring'''
										__lowercase       =       self.num_labels
										__lowercase       =       MobileNetVaForImageClassification(_lowerCamelCase       )
										model.to(_lowerCamelCase       )
										model.eval()
										__lowercase       =       model(_lowerCamelCase  ,    labels=_lowerCamelCase       )
										self.parent.assertEqual(result.logits.shape  ,    (self.batch_size, self.num_labels)       )





							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




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





@require_torch
class 					__a     ( __a					,   __a					,   unittest.TestCase       ):



							'''simple docstring'''







							_lowerCamelCase					:			Tuple          =   (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
							_lowerCamelCase					:			List[str]          =   (
							    {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							_lowerCamelCase					:			List[str]          =   False
							_lowerCamelCase					:			Any          =   False
							_lowerCamelCase					:			Any          =   False
							_lowerCamelCase					:			List[Any]          =   False
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




										'''simple docstring'''
										__lowercase       =       MobileNetVaModelTester(self       )
										__lowercase       =       MobileNetVaConfigTester(self  ,    config_class=_lowerCamelCase  ,    has_text_modality=_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




										'''simple docstring'''
										self.config_tester.run_common_tests()
							@unittest.skip(reason="MobileNetV1 does not use inputs_embeds"       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Dict:




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




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




										'''simple docstring'''
										pass
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										__lowercase   ,					__lowercase       =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													__lowercase       =       model_class(_lowerCamelCase       )
													__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]  ,    _lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Union[str, Any]:




										'''simple docstring'''
										__lowercase       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Dict:




										'''simple docstring'''
										def check_hidden_states_output(_lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       ):
													__lowercase       =       model_class(_lowerCamelCase       )
													model.to(_lowerCamelCase       )
													model.eval()

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

													__lowercase       =       outputs.hidden_states

													__lowercase       =       26
													self.assertEqual(len(_lowerCamelCase       )  ,    _lowerCamelCase       )

										__lowercase   ,					__lowercase       =       self.model_tester.prepare_config_and_inputs_for_common()

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

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

													check_hidden_states_output(_lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Dict:




										'''simple docstring'''
										__lowercase       =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase       )





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




										'''simple docstring'''
										for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowercase       =       MobileNetVaModel.from_pretrained(_lowerCamelCase       )
													self.assertIsNotNone(_lowerCamelCase       )





def      lowerCAmelCase__			(		)						->Any:
			__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   SCREAMING_SNAKE_CASE						(     self       )			->							Union[str, Any]:




										'''simple docstring'''
										return (
										    MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224"       ) if is_vision_available() else None
										)





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




										'''simple docstring'''
										__lowercase       =       MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"       ).to(_lowerCamelCase       )

										__lowercase       =       self.default_image_processor
										__lowercase       =       prepare_img()
										__lowercase       =       image_processor(images=_lowerCamelCase  ,    return_tensors="pt"       ).to(_lowerCamelCase       )

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

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

										__lowercase       =       torch.tensor([-4.1739, -1.1233, 3.1205]       ).to(_lowerCamelCase       )

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







"""simple docstring"""






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer

class 					__a     ( __a       ):



							'''simple docstring'''







							_lowerCamelCase					:			List[Any]          =   """Wav2Vec2FeatureExtractor"""
							_lowerCamelCase					:			Any          =   """AutoTokenizer"""
							def __init__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										super().__init__(_lowerCamelCase  ,    _lowerCamelCase       )
										__lowercase       =       self.feature_extractor
										__lowercase       =       False
							@classmethod
							def   SCREAMING_SNAKE_CASE						(     cls  ,    _lowerCamelCase  ,    **_lowerCamelCase       )			->							Any:




										'''simple docstring'''
										try:
													return super().from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
										except OSError:
													warnings.warn(
													    f'''Loading a tokenizer inside {cls.__name__} from a config that does not'''
													    " include a `tokenizer_class` attribute is deprecated and will be "
													    "removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`"
													    " attribute to either your `config.json` or `tokenizer_config.json` "
													    "file to suppress this warning: "  ,    _lowerCamelCase  ,    )

													__lowercase       =       WavaVecaFeatureExtractor.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
													__lowercase       =       WavaVecaCTCTokenizer.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )

													return cls(feature_extractor=_lowerCamelCase  ,    tokenizer=_lowerCamelCase       )
							def __call__(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[Any]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor(*_lowerCamelCase  ,    **_lowerCamelCase       )

										if "raw_speech" in kwargs:
													warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
													__lowercase       =       kwargs.pop("raw_speech"       )
										else:
													__lowercase       =       kwargs.pop("audio"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("sampling_rate"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("text"  ,    _lowerCamelCase       )
										if len(_lowerCamelCase       ) > 0:
													__lowercase       =       args[0]
													__lowercase       =       args[1:]

										if audio is None and text is None:
													raise ValueError("You need to specify either an `audio` or `text` input to process."       )

										if audio is not None:
													__lowercase       =       self.feature_extractor(_lowerCamelCase  ,    *_lowerCamelCase  ,    sampling_rate=_lowerCamelCase  ,    **_lowerCamelCase       )
										if text is not None:
													__lowercase       =       self.tokenizer(_lowerCamelCase  ,    **_lowerCamelCase       )

										if text is None:
													return inputs
										elif audio is None:
													return encodings
										else:
													__lowercase       =       encodings["input_ids"]
													return inputs
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor.pad(*_lowerCamelCase  ,    **_lowerCamelCase       )

										__lowercase       =       kwargs.pop("input_features"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("labels"  ,    _lowerCamelCase       )
										if len(_lowerCamelCase       ) > 0:
													__lowercase       =       args[0]
													__lowercase       =       args[1:]

										if input_features is not None:
													__lowercase       =       self.feature_extractor.pad(_lowerCamelCase  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )
										if labels is not None:
													__lowercase       =       self.tokenizer.pad(_lowerCamelCase  ,    **_lowerCamelCase       )

										if labels is None:
													return input_features
										elif input_features is None:
													return labels
										else:
													__lowercase       =       labels["input_ids"]
													return input_features
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Optional[int]:




										'''simple docstring'''
										return self.tokenizer.batch_decode(*_lowerCamelCase  ,    **_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Dict:




										'''simple docstring'''
										return self.tokenizer.decode(*_lowerCamelCase  ,    **_lowerCamelCase       )





							@contextmanager
							def   SCREAMING_SNAKE_CASE						(     self       )			->							str:




										'''simple docstring'''
										warnings.warn(
										    "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
										    "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
										    "your audio inputs, or in a separate call."       )
										__lowercase       =       True
										__lowercase       =       self.tokenizer
										yield
										__lowercase       =       self.feature_extractor
										__lowercase       =       False





