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





      '''simple docstring'''






      def __init__(					self     :				Optional[int]    ,  _UpperCamelCase     :				Tuple    ,  _UpperCamelCase     :				str=13    ,  _UpperCamelCase     :				str=32    ,  _UpperCamelCase     :				Tuple=3    ,  _UpperCamelCase     :				List[Any]=4    ,  _UpperCamelCase     :				List[Any]=[10, 20, 30, 40]    ,  _UpperCamelCase     :				int=[2, 2, 3, 2]    ,  _UpperCamelCase     :				Tuple=True    ,  _UpperCamelCase     :				List[str]=True    ,  _UpperCamelCase     :				Dict=37    ,  _UpperCamelCase     :				int="gelu"    ,  _UpperCamelCase     :				Optional[Any]=10    ,  _UpperCamelCase     :				Dict=0.0_2    ,  _UpperCamelCase     :				List[Any]=["stage2", "stage3", "stage4"]    ,  _UpperCamelCase     :				Union[str, Any]=[2, 3, 4]    ,  _UpperCamelCase     :				Optional[int]=None    ,  )				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						parent
          _lowerCamelCase     :		Union[str, Any] 						=						batch_size
          _lowerCamelCase     :		Union[str, Any] 						=						image_size
          _lowerCamelCase     :		Optional[Any] 						=						num_channels
          _lowerCamelCase     :		Optional[Any] 						=						num_stages
          _lowerCamelCase     :		int 						=						hidden_sizes
          _lowerCamelCase     :		Tuple 						=						depths
          _lowerCamelCase     :		List[str] 						=						is_training
          _lowerCamelCase     :		Tuple 						=						use_labels
          _lowerCamelCase     :		Tuple 						=						intermediate_size
          _lowerCamelCase     :		List[Any] 						=						hidden_act
          _lowerCamelCase     :		str 						=						num_labels
          _lowerCamelCase     :		List[str] 						=						initializer_range
          _lowerCamelCase     :		List[str] 						=						out_features
          _lowerCamelCase     :		Optional[int] 						=						out_indices
          _lowerCamelCase     :		List[Any] 						=						scope



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->Union[str, Any]:


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          _lowerCamelCase     :		Dict 						=						None
          if self.use_labels:
              _lowerCamelCase     :		List[str] 						=						ids_tensor([self.batch_size]    ,  self.num_labels)

          _lowerCamelCase     :		List[str] 						=						self.get_config()
          return config, pixel_values, labels



      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any])				->List[Any]:


          """simple docstring"""


          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=_UpperCamelCase    ,  initializer_range=self.initializer_range    ,  out_features=self.out_features    ,  out_indices=self.out_indices    ,  num_labels=self.num_labels    ,  )



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any]    ,  _UpperCamelCase     :				List[str]    ,  _UpperCamelCase     :				Dict    ,  _UpperCamelCase     :				Optional[Any])				->List[Any]:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						ConvNextModel(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          _lowerCamelCase     :		str 						=						model(_UpperCamelCase)
          # 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 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any]    ,  _UpperCamelCase     :				Union[str, Any]    ,  _UpperCamelCase     :				str    ,  _UpperCamelCase     :				Any)				->int:


          """simple docstring"""


          _lowerCamelCase     :		Optional[Any] 						=						ConvNextForImageClassification(_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          _lowerCamelCase     :		str 						=						model(_UpperCamelCase    ,  labels=_UpperCamelCase)
          self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.num_labels))



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int    ,  _UpperCamelCase     :				Tuple    ,  _UpperCamelCase     :				List[Any]    ,  _UpperCamelCase     :				Dict)				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						ConvNextBackbone(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          _lowerCamelCase     :		Optional[Any] 						=						model(_UpperCamelCase)

          # 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
          _lowerCamelCase     :		Optional[Any] 						=						None
          _lowerCamelCase     :		List[Any] 						=						ConvNextBackbone(config=_UpperCamelCase)
          model.to(_UpperCamelCase)
          model.eval()
          _lowerCamelCase     :		str 						=						model(_UpperCamelCase)

          # 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 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[int])				->List[str]:


          """simple docstring"""


          _lowerCamelCase     :		int 						=						self.prepare_config_and_inputs()
          _lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase     :		Dict 						=						config_and_inputs
          _lowerCamelCase     :		Union[str, Any] 						=						{"""pixel_values""": pixel_values}
          return config, inputs_dict





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





      '''simple docstring'''






      _snake_case    		=       (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      _snake_case    		=       (
          {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      _snake_case    		=       True
      _snake_case    		=       False
      _snake_case    		=       False
      _snake_case    		=       False
      _snake_case    		=       False



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any])				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		List[Any] 						=						ConvNextModelTester(self)
          _lowerCamelCase     :		List[str] 						=						ConfigTester(self    ,  config_class=_UpperCamelCase    ,  has_text_modality=_UpperCamelCase    ,  hidden_size=37)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->str:


          """simple docstring"""


          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 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->List[Any]:


          """simple docstring"""


          return



      @unittest.skip(reason="""ConvNext does not use inputs_embeds""")
      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->List[Any]:


          """simple docstring"""


          pass



      @unittest.skip(reason="""ConvNext does not support input and output embeddings""")
      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->int:


          """simple docstring"""


          pass



      @unittest.skip(reason="""ConvNext does not use feedforward chunking""")
      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[str])				->Tuple:


          """simple docstring"""


          pass



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->Tuple:


          """simple docstring"""


          _lowerCamelCase						,							_lowerCamelCase     :		Optional[Any] 						=						self.model_tester.prepare_config_and_inputs_for_common()

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

              _lowerCamelCase     :		Any 						=						["""pixel_values"""]
              self.assertListEqual(arg_names[:1]    ,  _UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any])				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->Optional[Any]:


          """simple docstring"""


          _lowerCamelCase     :		str 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->Tuple:


          """simple docstring"""


          def check_hidden_states_output(_UpperCamelCase     :				int    ,  _UpperCamelCase     :				Any    ,  _UpperCamelCase     :				str):
              _lowerCamelCase     :		Union[str, Any] 						=						model_class(_UpperCamelCase)
              model.to(_UpperCamelCase)
              model.eval()

              with torch.no_grad():
                  _lowerCamelCase     :		Dict 						=						model(**self._prepare_for_class(_UpperCamelCase    ,  _UpperCamelCase))

              _lowerCamelCase     :		List[str] 						=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _lowerCamelCase     :		Optional[Any] 						=						self.model_tester.num_stages
              self.assertEqual(len(_UpperCamelCase)    ,  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]    ,  )

          _lowerCamelCase						,							_lowerCamelCase     :		Optional[int] 						=						self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              _lowerCamelCase     :		Union[str, Any] 						=						True
              check_hidden_states_output(_UpperCamelCase    ,  _UpperCamelCase    ,  _UpperCamelCase)

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

              check_hidden_states_output(_UpperCamelCase    ,  _UpperCamelCase    ,  _UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any)				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase)




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[str])				->List[str]:


          """simple docstring"""


          for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowerCamelCase     :		int 						=						ConvNextModel.from_pretrained(_UpperCamelCase)
              self.assertIsNotNone(_UpperCamelCase)







def 						A__  (					):







    '''simple docstring'''
    _lowerCamelCase     :		int 						=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
    return image




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





      '''simple docstring'''






      @cached_property
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any])				->Any:


          """simple docstring"""


          return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""") if is_vision_available() else None




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->Dict:


          """simple docstring"""


          _lowerCamelCase     :		List[str] 						=						ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""").to(_UpperCamelCase)

          _lowerCamelCase     :		Optional[Any] 						=						self.default_image_processor
          _lowerCamelCase     :		str 						=						prepare_img()
          _lowerCamelCase     :		Optional[Any] 						=						image_processor(images=_UpperCamelCase    ,  return_tensors="""pt""").to(_UpperCamelCase)

          # forward pass
          with torch.no_grad():
              _lowerCamelCase     :		List[Any] 						=						model(**_UpperCamelCase)

          # verify the logits
          _lowerCamelCase     :		str 						=						torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape    ,  _UpperCamelCase)

          _lowerCamelCase     :		Any 						=						torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]).to(_UpperCamelCase)

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





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





      '''simple docstring'''






      _snake_case    		=       (ConvNextBackbone,) if is_torch_available() else ()
      _snake_case    		=       ConvNextConfig

      _snake_case    		=       False



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any)				->Union[str, Any]:


          """simple docstring"""


          _lowerCamelCase     :		Tuple 						=						ConvNextModelTester(self)





from __future__ import annotations

from math import pi
from typing import Protocol

import matplotlib.pyplot as plt
import numpy as np




class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any]    ,  _UpperCamelCase     :				float)				->float:


          """simple docstring"""


          return 0.0







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _lowerCamelCase     :		int 						=						min([-20, np.min(fft_results[1 : samplerate // 2 - 1]	)]	)
    _lowerCamelCase     :		Tuple 						=						max([20, np.max(fft_results[1 : samplerate // 2 - 1]	)]	)
    return lowest, highest







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _lowerCamelCase     :		Tuple 						=						512
    _lowerCamelCase     :		Tuple 						=						[1] + [0] * (size - 1)
    _lowerCamelCase     :		Optional[Any] 						=						[filter_type.process(__A	) for item in inputs]

    _lowerCamelCase     :		Optional[Any] 						=						[0] * (samplerate - size)  # zero-padding
    outputs += filler
    _lowerCamelCase     :		Tuple 						=						np.abs(np.fft.fft(__A	)	)
    _lowerCamelCase     :		List[Any] 						=						20 * np.logaa(__A	)

    # Frequencies on log scale from 24 to nyquist frequency
    plt.xlim(24   , samplerate / 2 - 1	)
    plt.xlabel("""Frequency (Hz)"""	)
    plt.xscale("""log"""	)

    # Display within reasonable bounds
    _lowerCamelCase     :		Any 						=						get_bounds(__A   , __A	)
    plt.ylim(max([-80, bounds[0]]	)   , min([80, bounds[1]]	)	)
    plt.ylabel("""Gain (dB)"""	)

    plt.plot(__A	)
    plt.show()







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _lowerCamelCase     :		Tuple 						=						512
    _lowerCamelCase     :		Union[str, Any] 						=						[1] + [0] * (size - 1)
    _lowerCamelCase     :		int 						=						[filter_type.process(__A	) for item in inputs]

    _lowerCamelCase     :		Optional[Any] 						=						[0] * (samplerate - size)  # zero-padding
    outputs += filler
    _lowerCamelCase     :		Any 						=						np.angle(np.fft.fft(__A	)	)

    # Frequencies on log scale from 24 to nyquist frequency
    plt.xlim(24   , samplerate / 2 - 1	)
    plt.xlabel("""Frequency (Hz)"""	)
    plt.xscale("""log"""	)

    plt.ylim(-2 * pi   , 2 * pi	)
    plt.ylabel("""Phase shift (Radians)"""	)
    plt.plot(np.unwrap(__A   , -2 * pi	)	)
    plt.show()




