




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       lowercase(  __snake_case				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



   _snake_case							:	int			=						self.config_class(**self.inputs_dict	)
   self.parent.assertTrue(hasattr(A_,   """tf_padding"""	)	)
   self.parent.assertTrue(hasattr(A_,   """depth_multiplier"""	)	)







class       lowercase:







 '''simple docstring'''





 def __init__(       self:	List[str],   a_:	Optional[Any],   a_:	Tuple=13,   a_:	Optional[Any]=3,   a_:	int=32,   a_:	Dict=0.25,   a_:	List[str]=8,   a_:	Tuple=True,   a_:	Union[str, Any]=1_024,   a_:	str=32,   a_:	Optional[Any]="relu6",   a_:	Union[str, Any]=0.1,   a_:	Optional[int]=0.02,   a_:	List[str]=True,   a_:	List[str]=True,   a_:	str=10,   a_:	str=None,   ):




   '''simple docstring'''



   _snake_case							:	Any			=						parent
   _snake_case							:	Optional[int]			=						batch_size
   _snake_case							:	Optional[int]			=						num_channels
   _snake_case							:	Tuple			=						image_size
   _snake_case							:	Any			=						depth_multiplier
   _snake_case							:	Any			=						min_depth
   _snake_case							:	Dict			=						tf_padding
   _snake_case							:	int			=						int(last_hidden_size * depth_multiplier	)
   _snake_case							:	Optional[int]			=						output_stride
   _snake_case							:	Any			=						hidden_act
   _snake_case							:	Any			=						classifier_dropout_prob
   _snake_case							:	Optional[int]			=						use_labels
   _snake_case							:	List[str]			=						is_training
   _snake_case							:	List[Any]			=						num_labels
   _snake_case							:	Optional[Any]			=						initializer_range
   _snake_case							:	Union[str, Any]			=						scope


 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

   _snake_case							:	int			=						None
   _snake_case							:	Dict			=						None
   if self.use_labels:
     _snake_case							:	Any			=						ids_tensor([self.batch_size],   self.num_labels	)
     _snake_case							:	Union[str, Any]			=						ids_tensor([self.batch_size, self.image_size, self.image_size],   self.num_labels	)

   _snake_case							:	Union[str, Any]			=						self.get_config()

   return config, pixel_values, labels, pixel_labels


 def 				UpperCamelCase_     (       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 				UpperCamelCase_     (       self:	Dict,   a_:	int,   a_:	Optional[int],   a_:	Optional[int],   a_:	Optional[int]	):




   '''simple docstring'''



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


 def 				UpperCamelCase_     (       self:	Dict,   a_:	List[Any],   a_:	List[Any],   a_:	Union[str, Any],   a_:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						self.num_labels
   _snake_case							:	List[str]			=						MobileNetVaForImageClassification(A_	)
   model.to(A_	)
   model.eval()
   _snake_case							:	Tuple			=						model(A_,   labels=A_	)
   self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						self.prepare_config_and_inputs()
   _snake_case							:	int			=						config_and_inputs
   _snake_case							:	Optional[Any]			=						{"pixel_values": pixel_values}
   return config, inputs_dict







@require_torch
class       lowercase(  __snake_case ,    __snake_case ,    unittest.TestCase				):







 '''simple docstring'''





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

 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						MobileNetVaModelTester(self	)
   _snake_case							:	List[str]			=						MobileNetVaConfigTester(self,   config_class=A_,   has_text_modality=A_	)


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   self.config_tester.run_common_tests()


 @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""	)
 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""	)
 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""MobileNetV1 does not output attentions"""	)
 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   pass


 def 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



   _snake_case							:	Any			=						self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _snake_case							:	List[str]			=						model_class(A_	)
     _snake_case							:	Dict			=						inspect.signature(model.forward	)
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     _snake_case							:	List[Any]			=						[*signature.parameters.keys()]

     _snake_case							:	Optional[Any]			=						["pixel_values"]
     self.assertListEqual(arg_names[:1],   A_	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*A_	)


 def 				UpperCamelCase_     (       self:	Any	):




   '''simple docstring'''



   def check_hidden_states_output(a_:	Tuple,   a_:	Optional[Any],   a_:	Any	):
     _snake_case							:	Dict			=						model_class(A_	)
     model.to(A_	)
     model.eval()

     with torch.no_grad():
       _snake_case							:	str			=						model(**self._prepare_for_class(A_,   A_	)	)

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

     _snake_case							:	List[str]			=						26
     self.assertEqual(len(A_	),   A_	)

   _snake_case							:	int			=						self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _snake_case							:	Optional[int]			=						True
     check_hidden_states_output(A_,   A_,   A_	)

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

     check_hidden_states_output(A_,   A_,   A_	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*A_	)


 @slow
 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:	Tuple			=						MobileNetVaModel.from_pretrained(A_	)
     self.assertIsNotNone(A_	)







def       UpperCAmelCase__ ():
  """simple docstring"""

  _snake_case							:	List[str]			=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
  return image






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







 '''simple docstring'''





 @cached_property
 def 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



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


 @slow
 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""	).to(A_	)

   _snake_case							:	List[Any]			=						self.default_image_processor
   _snake_case							:	Dict			=						prepare_img()
   _snake_case							:	Any			=						image_processor(images=A_,   return_tensors="""pt"""	).to(A_	)

   # forward pass
   with torch.no_grad():
     _snake_case							:	Any			=						model(**A_	)

   # verify the logits
   _snake_case							:	Optional[int]			=						torch.Size((1, 1_001)	)
   self.assertEqual(outputs.logits.shape,   A_	)

   _snake_case							:	Any			=						torch.tensor([-4.1_739, -1.1_233, 3.1_205]	).to(A_	)

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








"""simple docstring"""


import pyarrow.parquet as pq
import pytest

from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases


def       UpperCAmelCase__ (snake_case__							:      Optional[Any]	,     snake_case__							:      Dict					):
  """simple docstring"""

  assert isinstance(snake_case__	,     snake_case__					)
  assert dataset.num_rows == 4
  assert dataset.num_columns == 3
  assert dataset.column_names == ["col_1", "col_2", "col_3"]
  for feature, expected_dtype in expected_features.items():
    assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize("""keep_in_memory"""	,     [False, True]					)
def       UpperCAmelCase__ (snake_case__							:      str	,     snake_case__							:      Optional[int]	,     snake_case__							:      Dict					):
  """simple docstring"""

  _snake_case							:	str			=						tmp_path / """cache"""
  _snake_case							:	int			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
    _snake_case							:	str			=						ParquetDatasetReader(snake_case__	,     cache_dir=snake_case__	,     keep_in_memory=snake_case__					).read()
  _check_parquet_dataset(snake_case__	,     snake_case__					)


@pytest.mark.parametrize(
    """features"""	,     [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]	,     )
def       UpperCAmelCase__ (snake_case__							:      Dict	,     snake_case__							:      int	,     snake_case__							:      List[Any]					):
  """simple docstring"""

  _snake_case							:	str			=						tmp_path / """cache"""
  _snake_case							:	List[Any]			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  _snake_case							:	List[Any]			=						features.copy() if features else default_expected_features
  _snake_case							:	List[Any]			=						(
      Features({feature: Value(snake_case__					) for feature, dtype in features.items()}					) if features is not None else None
  )
  _snake_case							:	Optional[Any]			=						ParquetDatasetReader(snake_case__	,     features=snake_case__	,     cache_dir=snake_case__					).read()
  _check_parquet_dataset(snake_case__	,     snake_case__					)


@pytest.mark.parametrize("""split"""	,     [None, NamedSplit("""train"""					), """train""", """test"""]					)
def       UpperCAmelCase__ (snake_case__							:      Optional[int]	,     snake_case__							:      int	,     snake_case__							:      int					):
  """simple docstring"""

  _snake_case							:	List[str]			=						tmp_path / """cache"""
  _snake_case							:	Any			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  _snake_case							:	int			=						ParquetDatasetReader(snake_case__	,     cache_dir=snake_case__	,     split=snake_case__					).read()
  _check_parquet_dataset(snake_case__	,     snake_case__					)
  assert dataset.split == split if split else "train"


@pytest.mark.parametrize("""path_type"""	,     [str, list]					)
def       UpperCAmelCase__ (snake_case__							:      Dict	,     snake_case__							:      str	,     snake_case__							:      str					):
  """simple docstring"""

  if issubclass(snake_case__	,     snake_case__					):
    _snake_case							:	Optional[Any]			=						parquet_path
  elif issubclass(snake_case__	,     snake_case__					):
    _snake_case							:	int			=						[parquet_path]
  _snake_case							:	Union[str, Any]			=						tmp_path / """cache"""
  _snake_case							:	Tuple			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  _snake_case							:	List[str]			=						ParquetDatasetReader(snake_case__	,     cache_dir=snake_case__					).read()
  _check_parquet_dataset(snake_case__	,     snake_case__					)


def       UpperCAmelCase__ (snake_case__							:      str	,     snake_case__							:      Optional[int]	,     snake_case__							:      str=("train",)					):
  """simple docstring"""

  assert isinstance(snake_case__	,     snake_case__					)
  for split in splits:
    _snake_case							:	int			=						dataset_dict[split]
    assert dataset.num_rows == 4
    assert dataset.num_columns == 3
    assert dataset.column_names == ["col_1", "col_2", "col_3"]
    for feature, expected_dtype in expected_features.items():
      assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize("""keep_in_memory"""	,     [False, True]					)
def       UpperCAmelCase__ (snake_case__							:      str	,     snake_case__							:      str	,     snake_case__							:      List[Any]					):
  """simple docstring"""

  _snake_case							:	Tuple			=						tmp_path / """cache"""
  _snake_case							:	Optional[int]			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
    _snake_case							:	Tuple			=						ParquetDatasetReader(
        {"""train""": parquet_path}	,     cache_dir=snake_case__	,     keep_in_memory=snake_case__					).read()
  _check_parquet_datasetdict(snake_case__	,     snake_case__					)


@pytest.mark.parametrize(
    """features"""	,     [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]	,     )
def       UpperCAmelCase__ (snake_case__							:      List[str]	,     snake_case__							:      Tuple	,     snake_case__							:      List[Any]					):
  """simple docstring"""

  _snake_case							:	Optional[int]			=						tmp_path / """cache"""
  _snake_case							:	Dict			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  _snake_case							:	Optional[Any]			=						features.copy() if features else default_expected_features
  _snake_case							:	Dict			=						(
      Features({feature: Value(snake_case__					) for feature, dtype in features.items()}					) if features is not None else None
  )
  _snake_case							:	Optional[int]			=						ParquetDatasetReader({"""train""": parquet_path}	,     features=snake_case__	,     cache_dir=snake_case__					).read()
  _check_parquet_datasetdict(snake_case__	,     snake_case__					)


@pytest.mark.parametrize("""split"""	,     [None, NamedSplit("""train"""					), """train""", """test"""]					)
def       UpperCAmelCase__ (snake_case__							:      List[str]	,     snake_case__							:      Optional[Any]	,     snake_case__							:      Tuple					):
  """simple docstring"""

  if split:
    _snake_case							:	int			=						{split: parquet_path}
  else:
    _snake_case							:	Optional[Any]			=						"""train"""
    _snake_case							:	int			=						{"""train""": parquet_path, """test""": parquet_path}
  _snake_case							:	Dict			=						tmp_path / """cache"""
  _snake_case							:	Any			=						{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
  _snake_case							:	Union[str, Any]			=						ParquetDatasetReader(snake_case__	,     cache_dir=snake_case__					).read()
  _check_parquet_datasetdict(snake_case__	,     snake_case__	,     splits=list(path.keys()					)					)
  assert all(dataset[split].split == split for split in path.keys()					)


def       UpperCAmelCase__ (snake_case__							:      Tuple	,     snake_case__							:      Tuple					):
  """simple docstring"""

  _snake_case							:	List[Any]			=						ParquetDatasetWriter(snake_case__	,     tmp_path / """foo.parquet"""					)
  assert writer.write() > 0
  _snake_case							:	str			=						pq.ParquetFile(tmp_path / """foo.parquet"""					)
  _snake_case							:	int			=						pf.read()
  assert dataset.data.table == output_table


def       UpperCAmelCase__ (snake_case__							:      int	,     snake_case__							:      int					):
  """simple docstring"""

  _snake_case							:	Optional[Any]			=						str(shared_datadir / """test_image_rgb.jpg"""					)
  _snake_case							:	Tuple			=						{"""image""": [image_path]}
  _snake_case							:	Optional[int]			=						Features({"""image""": Image()}					)
  _snake_case							:	int			=						Dataset.from_dict(snake_case__	,     features=snake_case__					)
  _snake_case							:	Optional[Any]			=						ParquetDatasetWriter(snake_case__	,     tmp_path / """foo.parquet"""					)
  assert writer.write() > 0

  _snake_case							:	List[str]			=						Dataset.from_parquet(str(tmp_path / """foo.parquet"""					)					)
  assert dataset.features == reloaded_dataset.features

  _snake_case							:	Optional[Any]			=						ParquetDatasetReader(str(tmp_path / """foo.parquet"""					)	,     streaming=snake_case__					).read()
  assert dataset.features == reloaded_iterable_dataset.features






@pytest.mark.parametrize(
    """feature, expected"""	,     [
        (Features({"""foo""": Value("""int32"""					)}					), None),
        (Features({"""image""": Image(), """foo""": Value("""int32"""					)}					), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
        (Features({"""nested""": Sequence(Audio()					)}					), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
    ]	,     )
def       UpperCAmelCase__ (snake_case__							:      List[Any]	,     snake_case__							:      str					):
  """simple docstring"""

  assert get_writer_batch_size(snake_case__					) == expected


