




'''simple docstring'''






import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow






@is_pipeline_test
@require_torch
class        lowercase_      (						unittest.TestCase							):





     @require_torch
     def 			_lowerCAmelCase      (     self     :					Union[str, Any]			):
           snake_case__       :   Dict	      =    pipeline(
               task='zero-shot-audio-classification'     ,							model='hf-internal-testing/tiny-clap-htsat-unfused'			)
           snake_case__       :   Optional[int]	      =    load_dataset('ashraq/esc50'			)
           snake_case__       :   Dict	      =    dataset['train']['audio'][-1]['array']
           snake_case__       :   Any	      =    audio_classifier(__lowerCamelCase     ,							candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']			)
           self.assertEqual(
               nested_simplify(__lowerCamelCase			)     ,							[{'score': 0.5_0_1, 'label': 'Sound of a dog'}, {'score': 0.4_9_9, 'label': 'Sound of vaccum cleaner'}]     ,							)





     @unittest.skip('No models are available in TF'			)
     def 			_lowerCAmelCase      (     self     :					int			):
           pass





     @slow
     @require_torch
     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Optional[int]	      =    pipeline(
               task='zero-shot-audio-classification'     ,							model='laion/clap-htsat-unfused'     ,							)
           # This is an audio of a dog
           snake_case__       :   int	      =    load_dataset('ashraq/esc50'			)
           snake_case__       :   int	      =    dataset['train']['audio'][-1]['array']
           snake_case__       :   Any	      =    audio_classifier(__lowerCamelCase     ,							candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']			)

           self.assertEqual(
               nested_simplify(__lowerCamelCase			)     ,							[
                   {'score': 0.9_9_9, 'label': 'Sound of a dog'},
                   {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
               ]     ,							)

           snake_case__       :   str	      =    audio_classifier([audio] * 5     ,							candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']			)
           self.assertEqual(
               nested_simplify(__lowerCamelCase			)     ,							[
                   [
                       {'score': 0.9_9_9, 'label': 'Sound of a dog'},
                       {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
                   ],
               ]
               * 5     ,							)
           snake_case__       :   Optional[Any]	      =    audio_classifier(
               [audio] * 5     ,							candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']     ,							batch_size=5			)
           self.assertEqual(
               nested_simplify(__lowerCamelCase			)     ,							[
                   [
                       {'score': 0.9_9_9, 'label': 'Sound of a dog'},
                       {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'},
                   ],
               ]
               * 5     ,							)





     @unittest.skip('No models are available in TF'			)
     def 			_lowerCAmelCase      (     self     :					Union[str, Any]			):
           pass






'''simple docstring'''






import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
      from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor






class        lowercase_      :





     def __init__(     self     :					Tuple     ,							__lowerCamelCase     :					Optional[Any]     ,							__lowerCamelCase     :					Optional[Any]=13     ,							__lowerCamelCase     :					List[Any]=32     ,							__lowerCamelCase     :					List[str]=3     ,							__lowerCamelCase     :					Any=4     ,							__lowerCamelCase     :					str=[10, 20, 30, 40]     ,							__lowerCamelCase     :					Any=[2, 2, 3, 2]     ,							__lowerCamelCase     :					List[Any]=True     ,							__lowerCamelCase     :					List[Any]=True     ,							__lowerCamelCase     :					List[Any]=37     ,							__lowerCamelCase     :					int="gelu"     ,							__lowerCamelCase     :					List[Any]=10     ,							__lowerCamelCase     :					Tuple=0.0_2     ,							__lowerCamelCase     :					str=["stage2", "stage3", "stage4"]     ,							__lowerCamelCase     :					Optional[Any]=[2, 3, 4]     ,							__lowerCamelCase     :					Dict=None     ,							):
           snake_case__       :   List[str]	      =    parent
           snake_case__       :   Optional[Any]	      =    batch_size
           snake_case__       :   int	      =    image_size
           snake_case__       :   Tuple	      =    num_channels
           snake_case__       :   Any	      =    num_stages
           snake_case__       :   Any	      =    hidden_sizes
           snake_case__       :   Optional[Any]	      =    depths
           snake_case__       :   Optional[Any]	      =    is_training
           snake_case__       :   Dict	      =    use_labels
           snake_case__       :   Any	      =    intermediate_size
           snake_case__       :   int	      =    hidden_act
           snake_case__       :   Any	      =    num_labels
           snake_case__       :   Optional[int]	      =    initializer_range
           snake_case__       :   Union[str, Any]	      =    out_features
           snake_case__       :   Optional[Any]	      =    out_indices
           snake_case__       :   Optional[int]	      =    scope





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

           snake_case__       :   Optional[int]	      =    None
           if self.use_labels:
                 snake_case__       :   Tuple	      =    ids_tensor([self.batch_size]     ,							self.num_labels			)

           snake_case__       :   Any	      =    self.get_config()
           return config, pixel_values, labels





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           return ConvNextConfig(
               num_channels=self.num_channels     ,							hidden_sizes=self.hidden_sizes     ,							depths=self.depths     ,							num_stages=self.num_stages     ,							hidden_act=self.hidden_act     ,							is_decoder=__lowerCamelCase     ,							initializer_range=self.initializer_range     ,							out_features=self.out_features     ,							out_indices=self.out_indices     ,							num_labels=self.num_labels     ,							)





     def 			_lowerCAmelCase      (     self     :					List[Any]     ,							__lowerCamelCase     :					List[str]     ,							__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					Tuple			):
           snake_case__       :   Optional[int]	      =    ConvNextModel(config=__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   Union[str, Any]	      =    model(__lowerCamelCase			)
           # expected last hidden states: B, C, H // 32, W // 32
           self.parent.assertEqual(
               result.last_hidden_state.shape     ,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)     ,							)





     def 			_lowerCAmelCase      (     self     :					Any     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					List[Any]			):
           snake_case__       :   Optional[Any]	      =    ConvNextForImageClassification(__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   Optional[Any]	      =    model(__lowerCamelCase     ,							labels=__lowerCamelCase			)
           self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)			)





     def 			_lowerCAmelCase      (     self     :					List[str]     ,							__lowerCamelCase     :					int     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					int			):
           snake_case__       :   Dict	      =    ConvNextBackbone(config=__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   str	      =    model(__lowerCamelCase			)

           # verify hidden states
           self.parent.assertEqual(len(result.feature_maps			)     ,							len(config.out_features			)			)
           self.parent.assertListEqual(list(result.feature_maps[0].shape			)     ,							[self.batch_size, self.hidden_sizes[1], 4, 4]			)

           # verify channels
           self.parent.assertEqual(len(model.channels			)     ,							len(config.out_features			)			)
           self.parent.assertListEqual(model.channels     ,							config.hidden_sizes[1:]			)

           # verify backbone works with out_features=None
           snake_case__       :   List[str]	      =    None
           snake_case__       :   Union[str, Any]	      =    ConvNextBackbone(config=__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   int	      =    model(__lowerCamelCase			)

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps			)     ,							1			)
           self.parent.assertListEqual(list(result.feature_maps[0].shape			)     ,							[self.batch_size, self.hidden_sizes[-1], 1, 1]			)

           # verify channels
           self.parent.assertEqual(len(model.channels			)     ,							1			)
           self.parent.assertListEqual(model.channels     ,							[config.hidden_sizes[-1]]			)





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           snake_case__       :   Dict	      =    self.prepare_config_and_inputs()
           snake_case__      ,							snake_case__      ,							snake_case__       :   Optional[Any]	      =    config_and_inputs
           snake_case__       :   Optional[int]	      =    {'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class        lowercase_      (						lowerCAmelCase_						,       lowerCAmelCase_						,       unittest.TestCase							):
     A_											=			(
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     A_											=			(
         {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     A_											=			True
     A_											=			False
     A_											=			False
     A_											=			False
     A_											=			False





     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__       :   Tuple	      =    ConvNextModelTester(self			)
           snake_case__       :   Optional[int]	      =    ConfigTester(self     ,							config_class=__lowerCamelCase     ,							has_text_modality=__lowerCamelCase     ,							hidden_size=37			)





     def 			_lowerCAmelCase      (     self     :					Optional[Any]			):
           self.create_and_test_config_common_properties()
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()





     def 			_lowerCAmelCase      (     self     :					Dict			):
           return





     @unittest.skip(reason='ConvNext does not use inputs_embeds'			)
     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           pass





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





     @unittest.skip(reason='ConvNext does not use feedforward chunking'			)
     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           pass





     def 			_lowerCAmelCase      (     self     :					str			):
           snake_case__      ,							snake_case__       :   Any	      =    self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case__       :   str	      =    ['pixel_values']
                 self.assertListEqual(arg_names[:1]     ,							__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__       :   List[Any]	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__       :   List[Any]	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					str			):
           def check_hidden_states_output(__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					Any     ,							__lowerCamelCase     :					Tuple			):
                 snake_case__       :   int	      =    model_class(__lowerCamelCase			)
                 model.to(__lowerCamelCase			)
                 model.eval()

                 with torch.no_grad():
                       snake_case__       :   int	      =    model(**self._prepare_for_class(__lowerCamelCase     ,							__lowerCamelCase			)			)

                 snake_case__       :   Optional[Any]	      =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 snake_case__       :   Optional[Any]	      =    self.model_tester.num_stages
                 self.assertEqual(len(__lowerCamelCase			)     ,							expected_num_stages + 1			)

                 # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
                 self.assertListEqual(
                     list(hidden_states[0].shape[-2:]			)     ,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]     ,							)

           snake_case__      ,							snake_case__       :   List[Any]	      =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 snake_case__       :   Dict	      =    True
                 check_hidden_states_output(__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase			)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 snake_case__       :   Tuple	      =    True

                 check_hidden_states_output(__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           snake_case__       :   Any	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)





     @slow
     def 			_lowerCAmelCase      (     self     :					str			):
           for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case__       :   Optional[int]	      =    ConvNextModel.from_pretrained(__lowerCamelCase			)
                 self.assertIsNotNone(__lowerCamelCase			)






def 		UpperCamelCase__      (		)    ->   Optional[Any]:
      snake_case__       :   Any	      =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
      return image






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





     @cached_property
     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'			) if is_vision_available() else None





     @slow
     def 			_lowerCAmelCase      (     self     :					Optional[int]			):
           snake_case__       :   str	      =    ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'			).to(__lowerCamelCase			)

           snake_case__       :   str	      =    self.default_image_processor
           snake_case__       :   List[str]	      =    prepare_img()
           snake_case__       :   List[Any]	      =    image_processor(images=__lowerCamelCase     ,							return_tensors='pt'			).to(__lowerCamelCase			)

           # forward pass
           with torch.no_grad():
                 snake_case__       :   int	      =    model(**__lowerCamelCase			)

           # verify the logits
           snake_case__       :   Tuple	      =    torch.Size((1, 1000)			)
           self.assertEqual(outputs.logits.shape     ,							__lowerCamelCase			)

           snake_case__       :   int	      =    torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]			).to(__lowerCamelCase			)

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






@require_torch
class        lowercase_      (						unittest.TestCase						,       lowerCAmelCase_							):
     A_											=			(ConvNextBackbone,) if is_torch_available() else ()
     A_											=			ConvNextConfig

     A_											=			False





     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           snake_case__       :   List[Any]	      =    ConvNextModelTester(self			)
