






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:   str   )    ->				Any:
												_A								= self.config_class(**self.inputs_dict   )
												self.parent.assertTrue(hasattr(__A		,     '''tf_padding'''   )   )
												self.parent.assertTrue(hasattr(__A		,     '''depth_multiplier'''   )   )





class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							def __init__(  self:   Any		,     __A:   Tuple		,     __A:   Optional[int]=13		,     __A:   Optional[Any]=3		,     __A:   Optional[Any]=32		,     __A:   Optional[Any]=0.25		,     __A:   Optional[Any]=8		,     __A:   Dict=8		,     __A:   str=6		,     __A:   Union[str, Any]=32		,     __A:   Any=True		,     __A:   int=True		,     __A:   List[Any]=True		,     __A:   Union[str, Any]="relu6"		,     __A:   Dict=12_80		,     __A:   Dict=0.1		,     __A:   List[str]=0.02		,     __A:   List[str]=True		,     __A:   List[Any]=True		,     __A:   Optional[Any]=10		,     __A:   Union[str, Any]=None		,     )    ->				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:   str   )    ->				str:
												_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:   str   )    ->				Optional[Any]:
												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:   List[str]		,     __A:   Union[str, Any]		,     __A:   List[Any]		,     __A:   int		,     __A:   Optional[int]   )    ->				Optional[Any]:
												_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:   Optional[int]		,     __A:   Union[str, Any]		,     __A:   Optional[int]		,     __A:   Union[str, Any]		,     __A:   List[str]   )    ->				Any:
												_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:   Tuple		,     __A:   str		,     __A:   Dict		,     __A:   List[Any]   )    ->				Optional[Any]:
												_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   )    ->				Optional[Any]:
												_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 						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:   Any   )    ->				Union[str, Any]:
												_A								= MobileNetVaModelTester(self   )
												_A								= MobileNetVaConfigTester(self		,     config_class=__A		,     has_text_modality=__A   )

							def       __A (  self:   Dict   )    ->				Optional[Any]:
												self.config_tester.run_common_tests()

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

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

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

							def       __A (  self:   Any   )    ->				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(__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:   int   )    ->				str:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A   )

							def       __A (  self:   List[Any]   )    ->				Optional[Any]:
												def check_hidden_states_output(__A:   Tuple		,     __A:   List[str]		,     __A:   Optional[Any]   ):
																	_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:   Any   )    ->				Dict:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__A   )

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



							@slow
							def       __A (  self:   Union[str, Any]   )    ->				Optional[int]:
												for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A								= MobileNetVaModel.from_pretrained(__A   )
																	self.assertIsNotNone(__A   )




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:   int   )    ->				Any:
												return (
												    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''   ) if is_vision_available() else None
												)

							@slow
							def       __A (  self:   Tuple   )    ->				Union[str, Any]:
												_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_445, -1.1_993, 0.1_905]   ).to(__A   )

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



							@slow
							def       __A (  self:   Union[str, Any]   )    ->				Tuple:
												_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(
												    [
												        [[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=__A		,     )

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











import os
from pathlib import Path
from unittest.mock import patch

import pytest
import zstandard as zstd

from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
    OfflineModeIsEnabled,
    cached_path,
    fsspec_get,
    fsspec_head,
    ftp_get,
    ftp_head,
    get_from_cache,
    http_get,
    http_head,
)


__A      =				'\\n    Text data.\n    Second line of data.'

__A      =				'file'




@pytest.fixture(scope='''session''' )
def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
					_A								= bytes(_lowercase					,			'''utf-8''' )
					with zstd.open(_lowercase					,			'''wb''' ) as f:
										f.write(_lowercase )
					return path




@pytest.fixture
def      __A					(     _lowercase ):

					'''simple docstring'''







					with open(os.path.join(tmpfs.local_root_dir					,			_lowercase )					,			'''w''' ) as f:
										f.write(_lowercase )
					return FILE_PATH




@pytest.mark.parametrize('''compression_format'''					,			['''gzip''', '''xz''', '''zstd'''] )
def      __A					(     _lowercase					,			_lowercase					,			_lowercase					,			_lowercase					,			_lowercase					,			_lowercase ):

					'''simple docstring'''







					_A								= {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
					_A								= input_paths[compression_format]
					_A								= tmp_path / '''cache'''
					_A								= DownloadConfig(cache_dir=_lowercase					,			extract_compressed_file=_lowercase )
					_A								= cached_path(_lowercase					,			download_config=_lowercase )
					with open(_lowercase ) as f:
										_A								= f.read()
					with open(_lowercase ) as f:
										_A								= f.read()
					assert extracted_file_content == expected_file_content




@pytest.mark.parametrize('''default_extracted'''					,			[True, False] )
@pytest.mark.parametrize('''default_cache_dir'''					,			[True, False] )
def      __A					(     _lowercase					,			_lowercase					,			_lowercase					,			_lowercase					,			_lowercase ):

					'''simple docstring'''







					_A								= '''custom_cache'''
					_A								= '''custom_extracted_dir'''
					_A								= tmp_path / '''custom_extracted_path'''
					if default_extracted:
										_A								= ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
					else:
										monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR'''					,			_lowercase )
										monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH'''					,			str(_lowercase ) )
										_A								= custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)

					_A								= xz_file
					_A								= (
					    DownloadConfig(extract_compressed_file=_lowercase )
					    if default_cache_dir
					    else DownloadConfig(cache_dir=tmp_path / custom_cache_dir					,			extract_compressed_file=_lowercase )
					)
					_A								= cached_path(_lowercase					,			download_config=_lowercase )
					assert Path(_lowercase ).parent.parts[-2:] == expected




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= str(Path(_lowercase ).resolve() )
					assert cached_path(_lowercase ) == text_file
					# relative path
					_A								= str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
					assert cached_path(_lowercase ) == text_file




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= str(tmp_path.resolve() / '''__missing_file__.txt''' )
					with pytest.raises(_lowercase ):
										cached_path(_lowercase )
					# relative path
					_A								= '''./__missing_file__.txt'''
					with pytest.raises(_lowercase ):
										cached_path(_lowercase )




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= get_from_cache(f"""tmp://{tmpfs_file}""" )
					with open(_lowercase ) as f:
										_A								= f.read()
					assert output_file_content == FILE_CONTENT




@patch('''datasets.config.HF_DATASETS_OFFLINE'''					,			_lowercase )
def      __A					(     ):

					'''simple docstring'''







					with pytest.raises(_lowercase ):
										cached_path('''https://huggingface.co''' )




@patch('''datasets.config.HF_DATASETS_OFFLINE'''					,			_lowercase )
def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= tmp_path_factory.mktemp('''data''' ) / '''file.html'''
					with pytest.raises(_lowercase ):
										http_get('''https://huggingface.co'''					,			temp_file=_lowercase )
					with pytest.raises(_lowercase ):
										http_head('''https://huggingface.co''' )




@patch('''datasets.config.HF_DATASETS_OFFLINE'''					,			_lowercase )
def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= tmp_path_factory.mktemp('''data''' ) / '''file.html'''
					with pytest.raises(_lowercase ):
										ftp_get('''ftp://huggingface.co'''					,			temp_file=_lowercase )
					with pytest.raises(_lowercase ):
										ftp_head('''ftp://huggingface.co''' )




@patch('''datasets.config.HF_DATASETS_OFFLINE'''					,			_lowercase )
def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= tmp_path_factory.mktemp('''data''' ) / '''file.html'''
					with pytest.raises(_lowercase ):
										fsspec_get('''s3://huggingface.co'''					,			temp_file=_lowercase )
					with pytest.raises(_lowercase ):
										fsspec_head('''s3://huggingface.co''' )



