




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       a					:

     '''simple docstring'''





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

         UpperCAmelCase_										=					None
         if self.use_labels:
             UpperCAmelCase_										=					ids_tensor([self.batch_size] ,   self.num_labels    )

         UpperCAmelCase_										=					self.get_config()
         return config, pixel_values, labels
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
         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=__snake_case ,   initializer_range=self.initializer_range ,   out_features=self.out_features ,   out_indices=self.out_indices ,   num_labels=self.num_labels ,   )
     def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Optional[Any] ,   __snake_case       :      int ,   __snake_case       :      List[Any]    ):
         UpperCAmelCase_										=					ConvNextModel(config=__snake_case    )
         model.to(__snake_case    )
         model.eval()
         UpperCAmelCase_										=					model(__snake_case    )
         # 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       :      List[str] ,   __snake_case       :      List[Any] ,   __snake_case       :      List[Any] ,   __snake_case       :      Optional[Any]    ):
         UpperCAmelCase_										=					ConvNextForImageClassification(__snake_case    )
         model.to(__snake_case    )
         model.eval()
         UpperCAmelCase_										=					model(__snake_case ,   labels=__snake_case    )
         self.parent.assertEqual(result.logits.shape ,   (self.batch_size, self.num_labels)    )
     def   lowerCamelCase_       (     self       :      str ,   __snake_case       :      Union[str, Any] ,   __snake_case       :      Any ,   __snake_case       :      Union[str, Any]    ):
         UpperCAmelCase_										=					ConvNextBackbone(config=__snake_case    )
         model.to(__snake_case    )
         model.eval()
         UpperCAmelCase_										=					model(__snake_case    )

         # 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
         UpperCAmelCase_										=					None
         UpperCAmelCase_										=					ConvNextBackbone(config=__snake_case    )
         model.to(__snake_case    )
         model.eval()
         UpperCAmelCase_										=					model(__snake_case    )

         # 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       :      Optional[int]    ):
         UpperCAmelCase_										=					self.prepare_config_and_inputs()
         UpperCAmelCase_			,							UpperCAmelCase_			,							UpperCAmelCase_										=					config_and_inputs
         UpperCAmelCase_										=					{'''pixel_values''': pixel_values}
         return config, inputs_dict



@require_torch
class       a					(       _A     ,       _A     ,       unittest.TestCase      ):

     '''simple docstring'''





     lowerCAmelCase    :	List[Any]       		=  (
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     lowerCAmelCase    :	str       		=  (
         {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     lowerCAmelCase    :	Optional[Any]       		=  True
     lowerCAmelCase    :	Optional[int]       		=  False
     lowerCAmelCase    :	List[str]       		=  False
     lowerCAmelCase    :	List[Any]       		=  False
     lowerCAmelCase    :	Tuple       		=  False
     def   lowerCamelCase_       (     self       :      Any    ):
         UpperCAmelCase_										=					ConvNextModelTester(self    )
         UpperCAmelCase_										=					ConfigTester(self ,   config_class=__snake_case ,   has_text_modality=__snake_case ,   hidden_size=37    )
     def   lowerCamelCase_       (     self       :      int    ):
         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       :      List[str]    ):
         return
     @unittest.skip(reason='''ConvNext does not use inputs_embeds'''    )
     def   lowerCamelCase_       (     self       :      Optional[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       :      Union[str, Any]    ):
         pass
     def   lowerCamelCase_       (     self       :      Optional[int]    ):
         UpperCAmelCase_			,							UpperCAmelCase_										=					self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCAmelCase_										=					['''pixel_values''']
             self.assertListEqual(arg_names[:1] ,   __snake_case    )
     def   lowerCamelCase_       (     self       :      Tuple    ):
         UpperCAmelCase_										=					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case    )
     def   lowerCamelCase_       (     self       :      int    ):
         UpperCAmelCase_										=					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*__snake_case    )
     def   lowerCamelCase_       (     self       :      int    ):
         def check_hidden_states_output(__snake_case       :      Any ,   __snake_case       :      Union[str, Any] ,   __snake_case       :      Dict    ):
             UpperCAmelCase_										=					model_class(__snake_case    )
             model.to(__snake_case    )
             model.eval()

             with torch.no_grad():
                 UpperCAmelCase_										=					model(**self._prepare_for_class(__snake_case ,   __snake_case    )    )

             UpperCAmelCase_										=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             UpperCAmelCase_										=					self.model_tester.num_stages
             self.assertEqual(len(__snake_case    ) ,   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] ,   )

         UpperCAmelCase_			,							UpperCAmelCase_										=					self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCAmelCase_										=					True
             check_hidden_states_output(__snake_case ,   __snake_case ,   __snake_case    )

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

             check_hidden_states_output(__snake_case ,   __snake_case ,   __snake_case    )
     def   lowerCamelCase_       (     self       :      Optional[Any]    ):
         UpperCAmelCase_										=					self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__snake_case    )




     @slow
     def   lowerCamelCase_       (     self       :      int    ):
         for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase_										=					ConvNextModel.from_pretrained(__snake_case    )
             self.assertIsNotNone(__snake_case    )




def  SCREAMING_SNAKE_CASE     (	)  ->							Dict:
    UpperCAmelCase_										=					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
    return image



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

     '''simple docstring'''





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




     @slow
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
         UpperCAmelCase_										=					ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''    ).to(__snake_case    )

         UpperCAmelCase_										=					self.default_image_processor
         UpperCAmelCase_										=					prepare_img()
         UpperCAmelCase_										=					image_processor(images=__snake_case ,   return_tensors='''pt'''    ).to(__snake_case    )

         # forward pass
         with torch.no_grad():
             UpperCAmelCase_										=					model(**__snake_case    )

         # verify the logits
         UpperCAmelCase_										=					torch.Size((1, 10_00)    )
         self.assertEqual(outputs.logits.shape ,   __snake_case    )

         UpperCAmelCase_										=					torch.tensor([-0.0_260, -0.4_739, 0.1_911]    ).to(__snake_case    )

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



@require_torch
class       a					(       unittest.TestCase     ,       _A      ):

     '''simple docstring'''





     lowerCAmelCase    :	Dict       		=  (ConvNextBackbone,) if is_torch_available() else ()
     lowerCAmelCase    :	int       		=  ConvNextConfig

     lowerCAmelCase    :	Optional[Any]       		=  False
     def   lowerCamelCase_       (     self       :      int    ):
         UpperCAmelCase_										=					ConvNextModelTester(self    )











import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, ClassLabel, Features
from .base import TaskTemplate



@dataclass(frozen=_A      )
class       a					(       _A      ):

     '''simple docstring'''





     lowerCAmelCase    :	str       		=  field(default='audio-classification'     ,       metadata={'include_in_asdict_even_if_is_default': True}      )
     lowerCAmelCase    :	ClassVar[Features]       		=  Features({'audio': Audio()}      )
     lowerCAmelCase    :	ClassVar[Features]       		=  Features({'labels': ClassLabel}      )
     lowerCAmelCase    :	str       		=  "audio"
     lowerCAmelCase    :	str       		=  "labels"
     def   lowerCamelCase_       (     self       :      Optional[Any] ,   __snake_case       :      List[Any]    ):
         if self.label_column not in features:
             raise ValueError(F'Column {self.label_column} is not present in features.'    )
         if not isinstance(features[self.label_column] ,   __snake_case    ):
             raise ValueError(F'Column {self.label_column} is not a ClassLabel.'    )
         UpperCAmelCase_										=					copy.deepcopy(self    )
         UpperCAmelCase_										=					self.label_schema.copy()
         UpperCAmelCase_										=					features[self.label_column]
         UpperCAmelCase_										=					label_schema
         return task_template




     @property
     def   lowerCamelCase_       (     self       :      Tuple    ):
         return {
             self.audio_column: "audio",
             self.label_column: "labels",
         }





