

import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
  from transformers.models.mobilevitva.modeling_mobilevitva import (
      MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
      make_divisible,
  )


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor





class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):




  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        _lowercase      			=self.config_class(**self.inputs_dict   )
        self.parent.assertTrue(hasattr(lowerCAmelCase				,  'width_multiplier'   )   )





class 					__lowerCAmelCase	:




  def __init__(							self				,  lowerCAmelCase				,  lowerCAmelCase=13				,  lowerCAmelCase=64				,  lowerCAmelCase=2				,  lowerCAmelCase=3				,  lowerCAmelCase="swish"				,  lowerCAmelCase=3				,  lowerCAmelCase=32				,  lowerCAmelCase=0.1				,  lowerCAmelCase=0.02				,  lowerCAmelCase=True				,  lowerCAmelCase=True				,  lowerCAmelCase=10				,  lowerCAmelCase=None				,  lowerCAmelCase=0.25				,  lowerCAmelCase=0.0				,  lowerCAmelCase=0.0				,  )    ->					Dict:
        '''simple docstring'''






        _lowercase      			=parent
        _lowercase      			=batch_size
        _lowercase      			=image_size
        _lowercase      			=patch_size
        _lowercase      			=num_channels
        _lowercase      			=make_divisible(512 * width_multiplier				,  divisor=8   )
        _lowercase      			=hidden_act
        _lowercase      			=conv_kernel_size
        _lowercase      			=output_stride
        _lowercase      			=classifier_dropout_prob
        _lowercase      			=use_labels
        _lowercase      			=is_training
        _lowercase      			=num_labels
        _lowercase      			=initializer_range
        _lowercase      			=scope
        _lowercase      			=width_multiplier
        _lowercase      			=ffn_dropout
        _lowercase      			=attn_dropout




  def     A__	(							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     A__	(							self   )    ->					Union[str, Any]:
        '''simple docstring'''






        return MobileViTVaConfig(
            image_size=self.image_size				,  patch_size=self.patch_size				,  num_channels=self.num_channels				,  hidden_act=self.hidden_act				,  conv_kernel_size=self.conv_kernel_size				,  output_stride=self.output_stride				,  classifier_dropout_prob=self.classifier_dropout_prob				,  initializer_range=self.initializer_range				,  width_multiplier=self.width_multiplier				,  ffn_dropout=self.ffn_dropout_prob				,  attn_dropout=self.attn_dropout_prob				,  )




  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					str:
        '''simple docstring'''






        _lowercase      			=MobileViTVaModel(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     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=self.num_labels
        _lowercase      			=MobileViTVaForImageClassification(lowerCAmelCase   )
        model.to(lowerCAmelCase   )
        model.eval()
        _lowercase      			=model(lowerCAmelCase				,  labels=lowerCAmelCase   )
        self.parent.assertEqual(result.logits.shape				,  (self.batch_size, self.num_labels)   )




  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=self.num_labels
        _lowercase      			=MobileViTVaForSemanticSegmentation(lowerCAmelCase   )
        model.to(lowerCAmelCase   )
        model.eval()
        _lowercase      			=model(lowerCAmelCase   )
        self.parent.assertEqual(
            result.logits.shape				,  (
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )				,  )
        _lowercase      			=model(lowerCAmelCase				,  labels=lowerCAmelCase   )
        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   )    ->					List[Any]:
        '''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 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE     ,     unittest.TestCase				):
  _a		     =    (
      (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
      if is_torch_available()
      else ()
  )

  _a		     =    (
      {
          """feature-extraction""": MobileViTVaModel,
          """image-classification""": MobileViTVaForImageClassification,
          """image-segmentation""": MobileViTVaForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  _a		     =    False
  _a		     =    False
  _a		     =    False
  _a		     =    False




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






        _lowercase      			=MobileViTVaModelTester(self   )
        _lowercase      			=MobileViTVaConfigTester(self				,  config_class=lowerCAmelCase				,  has_text_modality=lowerCAmelCase   )




  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        self.config_tester.run_common_tests()




  @unittest.skip(reason='MobileViTV2 does not use inputs_embeds'   )
  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='MobileViTV2 does not support input and output embeddings'   )
  def     A__	(							self   )    ->					List[Any]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='MobileViTV2 does not output attentions'   )
  def     A__	(							self   )    ->					Dict:
        '''simple docstring'''






        pass




  @require_torch_multi_gpu
  @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'   )
  def     A__	(							self   )    ->					int:
        '''simple docstring'''






        pass




  @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        pass




  def     A__	(							self   )    ->					List[str]:
        '''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     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        _lowercase      			=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase   )




  def     A__	(							self   )    ->					Tuple:
        '''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      			=5
              self.assertEqual(len(lowerCAmelCase   )				,  lowerCAmelCase   )

              # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
              # with the width and height being successively divided by 2.
              _lowercase      			=2
              for i in range(len(lowerCAmelCase   )   ):
                    self.assertListEqual(
                        list(hidden_states[i].shape[-2:]   )				,  [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]				,  )
                    divisor *= 2

              self.assertEqual(self.model_tester.output_stride				,  divisor // 2   )

        _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     A__	(							self   )    ->					str:
        '''simple docstring'''






        _lowercase      			=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase   )




  def     A__	(							self   )    ->					Union[str, Any]:
        '''simple docstring'''






        _lowercase      			=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase   )




  @slow
  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowercase      			=MobileViTVaModel.from_pretrained(lowerCAmelCase   )
              self.assertIsNotNone(lowerCAmelCase   )
def 	a (     )       -> int:





      """simple docstring"""



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







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




  @cached_property
  def     A__	(							self   )    ->					List[Any]:
        '''simple docstring'''






        return (
            MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'   )
            if is_vision_available()
            else None
        )




  @slow
  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        _lowercase      			=MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'   ).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_000)   )
        self.assertEqual(outputs.logits.shape				,  lowerCAmelCase   )

        _lowercase      			=torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]   ).to(lowerCAmelCase   )

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




  @slow
  def     A__	(							self   )    ->					Union[str, Any]:
        '''simple docstring'''






        _lowercase      			=MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )
        _lowercase      			=model.to(lowerCAmelCase   )

        _lowercase      			=MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )

        _lowercase      			=prepare_img()
        _lowercase      			=image_processor(images=lowerCAmelCase				,  return_tensors='pt'   ).to(lowerCAmelCase   )

        # forward pass
        with torch.no_grad():
              _lowercase      			=model(**lowerCAmelCase   )
        _lowercase      			=outputs.logits

        # verify the logits
        _lowercase      			=torch.Size((1, 21, 32, 32)   )
        self.assertEqual(logits.shape				,  lowerCAmelCase   )

        _lowercase      			=torch.tensor(
            [
                [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
            ]				,  device=lowerCAmelCase				,  )

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




  @slow
  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        _lowercase      			=MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )
        _lowercase      			=model.to(lowerCAmelCase   )

        _lowercase      			=MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'   )

        _lowercase      			=prepare_img()
        _lowercase      			=image_processor(images=lowerCAmelCase				,  return_tensors='pt'   ).to(lowerCAmelCase   )

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

        _lowercase      			=outputs.logits.detach().cpu()

        _lowercase      			=image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase				,  target_sizes=[(50, 60)]   )
        _lowercase      			=torch.Size((50, 60)   )
        self.assertEqual(segmentation[0].shape				,  lowerCAmelCase   )

        _lowercase      			=image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase   )
        _lowercase      			=torch.Size((32, 32)   )
        self.assertEqual(segmentation[0].shape				,  lowerCAmelCase   )





from typing import List

import datasets
from datasets.tasks import AudioClassification

from ..folder_based_builder import folder_based_builder


lowercase_   							=  datasets.utils.logging.get_logger(__name__)





class 					__lowerCAmelCase	(   folder_based_builder.FolderBasedBuilderConfig				):
  _a		     =    None
  _a		     =    None





class 					__lowerCAmelCase	(   folder_based_builder.FolderBasedBuilder				):
  _a		     =    datasets.Audio()
  _a		     =    """audio"""
  _a		     =    AudioFolderConfig
  _a		     =    42  # definition at the bottom of the script
  _a		     =    AudioClassification(audio_column="""audio"""     ,     label_column="""label"""				)
lowercase_   							=  [
    '.aiff',
    '.au',
    '.avr',
    '.caf',
    '.flac',
    '.htk',
    '.svx',
    '.mat4',
    '.mat5',
    '.mpc2k',
    '.ogg',
    '.paf',
    '.pvf',
    '.raw',
    '.rf64',
    '.sd2',
    '.sds',
    '.ircam',
    '.voc',
    '.w64',
    '.wav',
    '.nist',
    '.wavex',
    '.wve',
    '.xi',
    '.mp3',
    '.opus',
]
lowercase_   							=  AUDIO_EXTENSIONS


