


"""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 			lowerCamelCase__						(   UpperCAmelCase_			):







						def __a						(							self   :    Dict		):
								A					       = self.config_class(**self.inputs_dict		)
								self.parent.assertTrue(hasattr(_lowercase			,			'tf_padding'		)		)
								self.parent.assertTrue(hasattr(_lowercase			,			'depth_multiplier'		)		)



class 			lowerCamelCase__						:







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







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







						def __a						(							self   :    Dict		):
								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 			lowerCamelCase__						(   UpperCAmelCase_							,    UpperCAmelCase_							,    unittest.TestCase			):
						lowerCAmelCase       =     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
						lowerCAmelCase       =     (
						    {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						lowerCAmelCase       =     False
						lowerCAmelCase       =     False
						lowerCAmelCase       =     False
						lowerCAmelCase       =     False







						def __a						(							self   :    Optional[Any]		):
								A					       = MobileNetVaModelTester(self		)
								A					       = MobileNetVaConfigTester(self			,			config_class=_lowercase			,			has_text_modality=_lowercase		)







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







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







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







						@unittest.skip(reason='MobileNetV1 does not output attentions'		)
						def __a						(							self   :    Any		):
								pass







						def __a						(							self   :    Union[str, Any]		):
								A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()

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







						def __a						(							self   :    Any		):
								A					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowercase		)







						def __a						(							self   :    Union[str, Any]		):
								def check_hidden_states_output(_lowercase   :    Tuple			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Tuple		):
										A					       = model_class(_lowercase		)
										model.to(_lowercase		)
										model.eval()

										with torch.no_grad():
												A					       = model(**self._prepare_for_class(_lowercase			,			_lowercase		)		)

										A					       = outputs.hidden_states

										A					       = 26
										self.assertEqual(len(_lowercase		)			,			_lowercase		)

								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(_lowercase			,			_lowercase			,			_lowercase		)

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

										check_hidden_states_output(_lowercase			,			_lowercase			,			_lowercase		)







						def __a						(							self   :    Any		):
								A					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*_lowercase		)







						@slow
						def __a						(							self   :    Dict		):
								for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										A					       = MobileNetVaModel.from_pretrained(_lowercase		)
										self.assertIsNotNone(_lowercase		)







def  __snake_case       (   )      ->		Optional[Any]:







		"""simple docstring"""





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



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







						@cached_property
						def __a						(							self   :    Union[str, Any]		):
								return (
								    MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'		) if is_vision_available() else None
								)







						@slow
						def __a						(							self   :    List[Any]		):
								A					       = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'		).to(_lowercase		)

								A					       = self.default_image_processor
								A					       = prepare_img()
								A					       = image_processor(images=_lowercase			,			return_tensors='pt'		).to(_lowercase		)

								# forward pass
								with torch.no_grad():
										A					       = model(**_lowercase		)

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

								A					       = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]		).to(_lowercase		)

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









"""simple docstring"""


import unittest

from huggingface_hub import hf_hub_download

from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_decord,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
)

from .test_pipelines_common import ANY



@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class 			lowerCamelCase__						(   unittest.TestCase			):
						lowerCAmelCase       =     MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING







						def __a						(							self   :    Dict			,			_lowercase   :    int			,			_lowercase   :    Any			,			_lowercase   :    int		):
								A					       = hf_hub_download(
								    repo_id='nateraw/video-demo'			,			filename='archery.mp4'			,			repo_type='dataset'		)
								A					       = VideoClassificationPipeline(model=_lowercase			,			image_processor=_lowercase			,			top_k=2		)
								A					       = [
								    example_video_filepath,
								    'https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4',
								]
								return video_classifier, examples







						def __a						(							self   :    Tuple			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    List[Any]		):
								for example in examples:
										A					       = video_classifier(_lowercase		)

										self.assertEqual(
										    _lowercase			,			[
										        {'score': ANY(_lowercase		), 'label': ANY(_lowercase		)},
										        {'score': ANY(_lowercase		), 'label': ANY(_lowercase		)},
										    ]			,			)







						@require_torch
						def __a						(							self   :    str		):
								A					       = 'hf-internal-testing/tiny-random-VideoMAEForVideoClassification'
								A					       = VideoMAEFeatureExtractor(
								    size={'shortest_edge': 10}			,			crop_size={'height': 10, 'width': 10}		)
								A					       = pipeline(
								    'video-classification'			,			model=_lowercase			,			feature_extractor=_lowercase			,			frame_sampling_rate=4		)

								A					       = hf_hub_download(repo_id='nateraw/video-demo'			,			filename='archery.mp4'			,			repo_type='dataset'		)
								A					       = video_classifier(_lowercase			,			top_k=2		)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}]			,			)

								A					       = video_classifier(
								    [
								        video_file_path,
								        video_file_path,
								    ]			,			top_k=2			,			)
								self.assertEqual(
								    nested_simplify(_lowercase			,			decimals=4		)			,			[
								        [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}],
								        [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}],
								    ]			,			)







						@require_tf
						def __a						(							self   :    Dict		):
								pass





