





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


	'''simple docstring'''





	def    snake_case__(						self:						Optional[int]			):
			lowercase__					:      Dict      =		self.config_class(**self.inputs_dict			)
			self.parent.assertTrue(hasattr(lowerCamelCase_,					'tf_padding'			)			)
			self.parent.assertTrue(hasattr(lowerCamelCase_,					'depth_multiplier'			)			)


class       __lowerCAmelCase					:


	'''simple docstring'''





	def __init__(						self:						Optional[Any],					lowerCamelCase_:						str,					lowerCamelCase_:						List[str]=13,					lowerCamelCase_:						List[Any]=3,					lowerCamelCase_:						Union[str, Any]=32,					lowerCamelCase_:						Union[str, Any]=0.2_5,					lowerCamelCase_:						Union[str, Any]=8,					lowerCamelCase_:						Any=True,					lowerCamelCase_:						Optional[int]=1024,					lowerCamelCase_:						List[Any]=32,					lowerCamelCase_:						List[str]="relu6",					lowerCamelCase_:						List[Any]=0.1,					lowerCamelCase_:						Union[str, Any]=0.0_2,					lowerCamelCase_:						Optional[Any]=True,					lowerCamelCase_:						Dict=True,					lowerCamelCase_:						List[Any]=10,					lowerCamelCase_:						Optional[int]=None,					):
			lowercase__					:      Any      =		parent
			lowercase__					:      Optional[int]      =		batch_size
			lowercase__					:      Optional[int]      =		num_channels
			lowercase__					:      Optional[Any]      =		image_size
			lowercase__					:      Optional[int]      =		depth_multiplier
			lowercase__					:      Union[str, Any]      =		min_depth
			lowercase__					:      int      =		tf_padding
			lowercase__					:      str      =		int(last_hidden_size * depth_multiplier			)
			lowercase__					:      int      =		output_stride
			lowercase__					:      Dict      =		hidden_act
			lowercase__					:      List[Any]      =		classifier_dropout_prob
			lowercase__					:      Any      =		use_labels
			lowercase__					:      int      =		is_training
			lowercase__					:      Optional[Any]      =		num_labels
			lowercase__					:      List[Any]      =		initializer_range
			lowercase__					:      Dict      =		scope

	def    snake_case__(						self:						List[Any]			):
			lowercase__					:      Union[str, Any]      =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

			lowercase__					:      Dict      =		None
			lowercase__					:      List[Any]      =		None
			if self.use_labels:
					lowercase__					:      Any      =		ids_tensor([self.batch_size],					self.num_labels			)
					lowercase__					:      Any      =		ids_tensor([self.batch_size, self.image_size, self.image_size],					self.num_labels			)

			lowercase__					:      str      =		self.get_config()

			return config, pixel_values, labels, pixel_labels

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





	def    snake_case__(						self:						List[str]			):
			lowercase__					:      List[Any]      =		self.prepare_config_and_inputs()
			lowercase__   ,				lowercase__   ,				lowercase__   ,				lowercase__					:      List[str]      =		config_and_inputs
			lowercase__					:      List[str]      =		{'pixel_values': pixel_values}
			return config, inputs_dict


@require_torch
class       __lowerCAmelCase					(       _UpperCamelCase   ,    _UpperCamelCase   ,    unittest.TestCase      ):


	'''simple docstring'''





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

	_A													=				False
	_A													=				False
	_A													=				False
	_A													=				False

	def    snake_case__(						self:						Union[str, Any]			):
			lowercase__					:      int      =		MobileNetVaModelTester(self			)
			lowercase__					:      Dict      =		MobileNetVaConfigTester(self,					config_class=lowerCamelCase_,					has_text_modality=lowerCamelCase_			)

	def    snake_case__(						self:						str			):
			self.config_tester.run_common_tests()

	@unittest.skip(reason='MobileNetV1 does not use inputs_embeds'			)
	def    snake_case__(						self:						str			):
			pass

	@unittest.skip(reason='MobileNetV1 does not support input and output embeddings'			)
	def    snake_case__(						self:						Tuple			):
			pass

	@unittest.skip(reason='MobileNetV1 does not output attentions'			)
	def    snake_case__(						self:						Optional[int]			):
			pass

	def    snake_case__(						self:						Union[str, Any]			):
			lowercase__   ,				lowercase__					:      Dict      =		self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowercase__					:      int      =		model_class(lowerCamelCase_			)
					lowercase__					:      Optional[Any]      =		inspect.signature(model.forward			)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					lowercase__					:      Union[str, Any]      =		[*signature.parameters.keys()]

					lowercase__					:      str      =		['pixel_values']
					self.assertListEqual(arg_names[:1],					lowerCamelCase_			)

	def    snake_case__(						self:						str			):
			lowercase__					:      Union[str, Any]      =		self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase_			)

	def    snake_case__(						self:						Tuple			):
			def check_hidden_states_output(lowerCamelCase_:						List[str],					lowerCamelCase_:						int,					lowerCamelCase_:						List[str]			):
					lowercase__					:      Optional[Any]      =		model_class(lowerCamelCase_			)
					model.to(lowerCamelCase_			)
					model.eval()

					with torch.no_grad():
							lowercase__					:      Dict      =		model(**self._prepare_for_class(lowerCamelCase_,					lowerCamelCase_			)			)

					lowercase__					:      Union[str, Any]      =		outputs.hidden_states

					lowercase__					:      Dict      =		26
					self.assertEqual(len(lowerCamelCase_			),					lowerCamelCase_			)

			lowercase__   ,				lowercase__					:      Dict      =		self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowercase__					:      int      =		True
					check_hidden_states_output(lowerCamelCase_,					lowerCamelCase_,					lowerCamelCase_			)

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					lowercase__					:      List[str]      =		True

					check_hidden_states_output(lowerCamelCase_,					lowerCamelCase_,					lowerCamelCase_			)

	def    snake_case__(						self:						Any			):
			lowercase__					:      Optional[int]      =		self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_			)





	@slow
	def    snake_case__(						self:						Tuple			):
			for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					lowercase__					:      Optional[int]      =		MobileNetVaModel.from_pretrained(lowerCamelCase_			)
					self.assertIsNotNone(lowerCamelCase_			)


def       SCREAMING_SNAKE_CASE__  (       )   ->							Optional[int]:




		'''simple docstring'''
		lowercase__					:      Union[str, Any]      =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
		return image





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


	'''simple docstring'''





	@cached_property
	def    snake_case__(						self:						str			):
			return (
			    MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'			) if is_vision_available() else None
			)





	@slow
	def    snake_case__(						self:						List[str]			):
			lowercase__					:      Union[str, Any]      =		MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'			).to(lowerCamelCase_			)

			lowercase__					:      int      =		self.default_image_processor
			lowercase__					:      List[str]      =		prepare_img()
			lowercase__					:      Tuple      =		image_processor(images=lowerCamelCase_,					return_tensors='pt'			).to(lowerCamelCase_			)

			# forward pass
			with torch.no_grad():
					lowercase__					:      Optional[Any]      =		model(**lowerCamelCase_			)

			# verify the logits
			lowercase__					:      Optional[Any]      =		torch.Size((1, 1001)			)
			self.assertEqual(outputs.logits.shape,					lowerCamelCase_			)

			lowercase__					:      Optional[Any]      =		torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]			).to(lowerCamelCase_			)

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









import unittest

import numpy as np

from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
from transformers.pipelines import AudioClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torchaudio,
    slow,
)

from .test_pipelines_common import ANY


@is_pipeline_test
class       __lowerCAmelCase					(       unittest.TestCase      ):


	'''simple docstring'''





	_A													=				MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
	_A													=				TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING

	def    snake_case__(						self:						Optional[int],					lowerCamelCase_:						Tuple,					lowerCamelCase_:						List[Any],					lowerCamelCase_:						Optional[Any]			):
			lowercase__					:      int      =		AudioClassificationPipeline(model=lowerCamelCase_,					feature_extractor=lowerCamelCase_			)

			# test with a raw waveform
			lowercase__					:      Dict      =		np.zeros((34000,)			)
			lowercase__					:      Optional[int]      =		np.zeros((14000,)			)
			return audio_classifier, [audioa, audio]

	def    snake_case__(						self:						Optional[int],					lowerCamelCase_:						Tuple,					lowerCamelCase_:						str			):
			lowercase__   ,				lowercase__					:      List[str]      =		examples
			lowercase__					:      int      =		audio_classifier(lowerCamelCase_			)
			# by default a model is initialized with num_labels=2
			self.assertEqual(
			    lowerCamelCase_,					[
			        {'score': ANY(lowerCamelCase_			), 'label': ANY(lowerCamelCase_			)},
			        {'score': ANY(lowerCamelCase_			), 'label': ANY(lowerCamelCase_			)},
			    ],					)
			lowercase__					:      List[Any]      =		audio_classifier(lowerCamelCase_,					top_k=1			)
			self.assertEqual(
			    lowerCamelCase_,					[
			        {'score': ANY(lowerCamelCase_			), 'label': ANY(lowerCamelCase_			)},
			    ],					)

			self.run_torchaudio(lowerCamelCase_			)

	@require_torchaudio
	def    snake_case__(						self:						Dict,					lowerCamelCase_:						str			):
			import datasets

			# test with a local file
			lowercase__					:      Optional[Any]      =		datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy',					'clean',					split='validation'			)
			lowercase__					:      int      =		dataset[0]['audio']['array']
			lowercase__					:      Tuple      =		audio_classifier(lowerCamelCase_			)
			self.assertEqual(
			    lowerCamelCase_,					[
			        {'score': ANY(lowerCamelCase_			), 'label': ANY(lowerCamelCase_			)},
			        {'score': ANY(lowerCamelCase_			), 'label': ANY(lowerCamelCase_			)},
			    ],					)

	@require_torch
	def    snake_case__(						self:						Optional[int]			):
			lowercase__					:      List[str]      =		'anton-l/wav2vec2-random-tiny-classifier'

			lowercase__					:      Tuple      =		pipeline('audio-classification',					model=lowerCamelCase_			)

			lowercase__					:      List[str]      =		np.ones((8000,)			)
			lowercase__					:      List[Any]      =		audio_classifier(lowerCamelCase_,					top_k=4			)

			lowercase__					:      List[str]      =		[
			    {'score': 0.0_8_4_2, 'label': 'no'},
			    {'score': 0.0_8_3_8, 'label': 'up'},
			    {'score': 0.0_8_3_7, 'label': 'go'},
			    {'score': 0.0_8_3_4, 'label': 'right'},
			]
			lowercase__					:      Optional[int]      =		[
			    {'score': 0.0_8_4_5, 'label': 'stop'},
			    {'score': 0.0_8_4_4, 'label': 'on'},
			    {'score': 0.0_8_4_1, 'label': 'right'},
			    {'score': 0.0_8_3_4, 'label': 'left'},
			]
			self.assertIn(nested_simplify(lowerCamelCase_,					decimals=4			),					[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]			)

			lowercase__					:      Tuple      =		{'array': np.ones((8000,)			), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
			lowercase__					:      Any      =		audio_classifier(lowerCamelCase_,					top_k=4			)
			self.assertIn(nested_simplify(lowerCamelCase_,					decimals=4			),					[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]			)

	@require_torch
	@slow
	def    snake_case__(						self:						Optional[int]			):
			import datasets

			lowercase__					:      str      =		'superb/wav2vec2-base-superb-ks'

			lowercase__					:      Optional[int]      =		pipeline('audio-classification',					model=lowerCamelCase_			)
			lowercase__					:      List[Any]      =		datasets.load_dataset('anton-l/superb_dummy',					'ks',					split='test'			)

			lowercase__					:      Optional[Any]      =		np.array(dataset[3]['speech'],					dtype=np.floataa			)
			lowercase__					:      Optional[int]      =		audio_classifier(lowerCamelCase_,					top_k=4			)
			self.assertEqual(
			    nested_simplify(lowerCamelCase_,					decimals=3			),					[
			        {'score': 0.9_8_1, 'label': 'go'},
			        {'score': 0.0_0_7, 'label': 'up'},
			        {'score': 0.0_0_6, 'label': '_unknown_'},
			        {'score': 0.0_0_1, 'label': 'down'},
			    ],					)





	@require_tf
	@unittest.skip('Audio classification is not implemented for TF'			)
	def    snake_case__(						self:						int			):
			pass


