'''simple docstring'''




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor

class 	lowerCamelCase_	:
      '''simple docstring'''

      def __init__(       self						:				List[str]						,					A						:				List[Any]						,					A						:				List[str]=3						,					A						:				List[str]=32						,					A						:				Optional[int]=3						,					A						:				str=10						,					A						:				Any=[10, 20, 30, 40]						,					A						:				int=[1, 1, 2, 1]						,					A						:				int=True						,					A						:				Dict=True						,					A						:				Optional[int]="relu"						,					A						:				Optional[int]=3						,					A						:				Tuple=None						,					):
             _UpperCAmelCase     :  Tuple							      =    parent
             _UpperCAmelCase     :  Union[str, Any]							      =    batch_size
             _UpperCAmelCase     :  List[Any]							      =    image_size
             _UpperCAmelCase     :  Dict							      =    num_channels
             _UpperCAmelCase     :  List[str]							      =    embeddings_size
             _UpperCAmelCase     :  Tuple							      =    hidden_sizes
             _UpperCAmelCase     :  Optional[int]							      =    depths
             _UpperCAmelCase     :  Tuple							      =    is_training
             _UpperCAmelCase     :  str							      =    use_labels
             _UpperCAmelCase     :  Union[str, Any]							      =    hidden_act
             _UpperCAmelCase     :  Optional[int]							      =    num_labels
             _UpperCAmelCase     :  Dict							      =    scope
             _UpperCAmelCase     :  List[Any]							      =    len(A       )




      def      _A	(       self						:				int       ):
             _UpperCAmelCase     :  Optional[int]							      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

             _UpperCAmelCase     :  Optional[Any]							      =    None
             if self.use_labels:
                    _UpperCAmelCase     :  Dict							      =    ids_tensor([self.batch_size]						,					self.num_labels       )

             _UpperCAmelCase     :  Tuple							      =    self.get_config()
             return config, pixel_values, labels




      def      _A	(       self						:				str       ):
             return RegNetConfig(
                 num_channels=self.num_channels						,					embeddings_size=self.embeddings_size						,					hidden_sizes=self.hidden_sizes						,					depths=self.depths						,					hidden_act=self.hidden_act						,					num_labels=self.num_labels						,					)




      def      _A	(       self						:				Optional[int]						,					A						:				Any						,					A						:				int						,					A						:				str       ):
             _UpperCAmelCase     :  int							      =    TFRegNetModel(config=A       )
             _UpperCAmelCase     :  Optional[int]							      =    model(A						,					training=A       )
             # 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      _A	(       self						:				Union[str, Any]						,					A						:				str						,					A						:				Optional[Any]						,					A						:				Optional[int]       ):
             _UpperCAmelCase     :  Any							      =    self.num_labels
             _UpperCAmelCase     :  str							      =    TFRegNetForImageClassification(A       )
             _UpperCAmelCase     :  Tuple							      =    model(A						,					labels=A						,					training=A       )
             self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)       )





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

@require_tf
class 	lowerCamelCase_	(snake_case__							, snake_case__							, unittest.TestCase    ):
      '''simple docstring'''

      __UpperCamelCase:  int						=						(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      __UpperCamelCase:  Union[str, Any]						=						(
          {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      __UpperCamelCase:  Dict						=						False
      __UpperCamelCase:  Optional[int]						=						False
      __UpperCamelCase:  Any						=						False
      __UpperCamelCase:  Optional[Any]						=						False
      __UpperCamelCase:  Tuple						=						False




      def      _A	(       self						:				Any       ):
             _UpperCAmelCase     :  Any							      =    TFRegNetModelTester(self       )
             _UpperCAmelCase     :  List[str]							      =    ConfigTester(self						,					config_class=A						,					has_text_modality=A       )




      def      _A	(       self						:				List[Any]       ):
             return




      @unittest.skip(reason="RegNet does not use inputs_embeds"       )
      def      _A	(       self						:				List[Any]       ):
             pass




      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("GPU"       )       ) == 0						,					reason="TF does not support backprop for grouped convolutions on CPU."						,					)
      @slow
      def      _A	(       self						:				Optional[Any]       ):
             super().test_keras_fit()




      @unittest.skip(reason="RegNet does not support input and output embeddings"       )
      def      _A	(       self						:				str       ):
             pass




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase      ,  _UpperCAmelCase     :  List[str]							      =    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _UpperCAmelCase     :  Union[str, Any]							      =    model_class(A       )
                    _UpperCAmelCase     :  List[str]							      =    inspect.signature(model.call       )
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    _UpperCAmelCase     :  Union[str, Any]							      =    [*signature.parameters.keys()]

                    _UpperCAmelCase     :  Optional[int]							      =    ["pixel_values"]
                    self.assertListEqual(arg_names[:1]						,					A       )




      def      _A	(       self						:				Union[str, Any]       ):
             _UpperCAmelCase     :  int							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A       )




      def      _A	(       self						:				List[Any]       ):
             def check_hidden_states_output(A						:				Any						,					A						:				Any						,					A						:				Optional[Any]       ):
                    _UpperCAmelCase     :  Union[str, Any]							      =    model_class(A       )
                    _UpperCAmelCase     :  Optional[int]							      =    model(**self._prepare_for_class(A						,					A       )						,					training=A       )

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

                    _UpperCAmelCase     :  int							      =    self.model_tester.num_stages
                    self.assertEqual(len(A       )						,					expected_num_stages + 1       )

                    # RegNet'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 // 2, self.model_tester.image_size // 2]						,					)

             _UpperCAmelCase      ,  _UpperCAmelCase     :  Optional[Any]							      =    self.model_tester.prepare_config_and_inputs_for_common()
             _UpperCAmelCase     :  List[str]							      =    ["basic", "bottleneck"]
             for model_class in self.all_model_classes:
                    for layer_type in layers_type:
                           _UpperCAmelCase     :  List[str]							      =    layer_type
                           _UpperCAmelCase     :  Dict							      =    True
                           check_hidden_states_output(A						,					A						,					A       )

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

                           check_hidden_states_output(A						,					A						,					A       )




      def      _A	(       self						:				Tuple       ):
             _UpperCAmelCase      ,  _UpperCAmelCase     :  Tuple							      =    self.model_tester.prepare_config_and_inputs_for_common()

             def check_equivalence(A						:				Optional[int]						,					A						:				Union[str, Any]						,					A						:				Optional[Any]						,					A						:				str={}       ):
                    _UpperCAmelCase     :  Tuple							      =    model(A						,					return_dict=A						,					**A       )
                    _UpperCAmelCase     :  Any							      =    model(A						,					return_dict=A						,					**A       ).to_tuple()

                    def recursive_check(A						:				Tuple						,					A						:				Tuple       ):
                           if isinstance(A						,					(List, Tuple)       ):
                                  for tuple_iterable_value, dict_iterable_value in zip(A						,					A       ):
                                         recursive_check(A						,					A       )
                           elif tuple_object is None:
                                  return
                           else:
                                  self.assertTrue(
                                      all(tf.equal(A						,					A       )       )						,					msg=(
                                          "Tuple and dict output are not equal. Difference:"
                                          F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object       )       )}"""
                                      )						,					)

                           recursive_check(A						,					A       )

             for model_class in self.all_model_classes:
                    _UpperCAmelCase     :  Tuple							      =    model_class(A       )

                    _UpperCAmelCase     :  Optional[Any]							      =    self._prepare_for_class(A						,					A       )
                    _UpperCAmelCase     :  str							      =    self._prepare_for_class(A						,					A       )
                    check_equivalence(A						,					A						,					A       )

                    _UpperCAmelCase     :  Optional[int]							      =    self._prepare_for_class(A						,					A						,					return_labels=A       )
                    _UpperCAmelCase     :  Optional[int]							      =    self._prepare_for_class(A						,					A						,					return_labels=A       )
                    check_equivalence(A						,					A						,					A       )

                    _UpperCAmelCase     :  Optional[Any]							      =    self._prepare_for_class(A						,					A       )
                    _UpperCAmelCase     :  Tuple							      =    self._prepare_for_class(A						,					A       )
                    check_equivalence(A						,					A						,					A						,					{"output_hidden_states": True}       )

                    _UpperCAmelCase     :  int							      =    self._prepare_for_class(A						,					A						,					return_labels=A       )
                    _UpperCAmelCase     :  Union[str, Any]							      =    self._prepare_for_class(A						,					A						,					return_labels=A       )
                    check_equivalence(A						,					A						,					A						,					{"output_hidden_states": True}       )




      def      _A	(       self						:				Tuple       ):
             _UpperCAmelCase     :  int							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A       )





      @slow
      def      _A	(       self						:				List[str]       ):
             for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _UpperCAmelCase     :  Any							      =    TFRegNetModel.from_pretrained(A       )
                    self.assertIsNotNone(A       )

def 	UpperCamelCase_							(					)    ->    str:


       """simple docstring"""







       _UpperCAmelCase     :  Any							      =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
       return image


@require_tf
@require_vision
class 	lowerCamelCase_	(unittest.TestCase    ):
      '''simple docstring'''

      @cached_property
      def      _A	(       self						:				Optional[int]       ):
             return (
                 AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
                 if is_vision_available()
                 else None
             )





      @slow
      def      _A	(       self						:				List[str]       ):
             _UpperCAmelCase     :  Dict							      =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

             _UpperCAmelCase     :  Tuple							      =    self.default_image_processor
             _UpperCAmelCase     :  int							      =    prepare_img()
             _UpperCAmelCase     :  Optional[Any]							      =    image_processor(images=A						,					return_tensors="tf"       )

             # forward pass
             _UpperCAmelCase     :  Optional[Any]							      =    model(**A						,					training=A       )

             # verify the logits
             _UpperCAmelCase     :  Union[str, Any]							      =    tf.TensorShape((1, 1000)       )
             self.assertEqual(outputs.logits.shape						,					A       )

             _UpperCAmelCase     :  Optional[Any]							      =    tf.constant([-0.4_180, -1.5_051, -3.4_836]       )

             tf.debugging.assert_near(outputs.logits[0, :3]						,					A						,					atol=1E-4       )


'''simple docstring'''




import math
from typing import Optional

import numpy as np

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE       :     Dict     =  logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE       :     List[Any]     =  {
    """facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""",
    """facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""",
}

class 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  str						=						"encodec"




      def __init__(       self						:				Optional[int]						,					A						:				Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0]						,					A						:				List[Any]=24000						,					A						:				Union[str, Any]=1						,					A						:				List[Any]=False						,					A						:				Optional[int]=None						,					A						:				int=None						,					A						:				str=128						,					A						:				List[Any]=32						,					A						:				List[Any]=1						,					A						:				int=[8, 5, 4, 2]						,					A						:				Optional[int]="weight_norm"						,					A						:				List[Any]=7						,					A						:				Any=7						,					A						:				Dict=3						,					A						:				Optional[int]=2						,					A						:				Dict=True						,					A						:				Dict="reflect"						,					A						:				Any=2						,					A						:				Dict=2						,					A						:				str=1.0						,					A						:				Optional[int]=1024						,					A						:				Any=None						,					A						:				Any=True						,					**A						:				str						,					):
             _UpperCAmelCase     :  Optional[int]							      =    target_bandwidths
             _UpperCAmelCase     :  List[str]							      =    sampling_rate
             _UpperCAmelCase     :  Optional[int]							      =    audio_channels
             _UpperCAmelCase     :  str							      =    normalize
             _UpperCAmelCase     :  int							      =    chunk_length_s
             _UpperCAmelCase     :  str							      =    overlap
             _UpperCAmelCase     :  Optional[Any]							      =    hidden_size
             _UpperCAmelCase     :  int							      =    num_filters
             _UpperCAmelCase     :  Optional[Any]							      =    num_residual_layers
             _UpperCAmelCase     :  Optional[int]							      =    upsampling_ratios
             _UpperCAmelCase     :  int							      =    norm_type
             _UpperCAmelCase     :  List[Any]							      =    kernel_size
             _UpperCAmelCase     :  List[Any]							      =    last_kernel_size
             _UpperCAmelCase     :  List[Any]							      =    residual_kernel_size
             _UpperCAmelCase     :  List[str]							      =    dilation_growth_rate
             _UpperCAmelCase     :  Dict							      =    use_causal_conv
             _UpperCAmelCase     :  Tuple							      =    pad_mode
             _UpperCAmelCase     :  Tuple							      =    compress
             _UpperCAmelCase     :  List[str]							      =    num_lstm_layers
             _UpperCAmelCase     :  List[Any]							      =    trim_right_ratio
             _UpperCAmelCase     :  int							      =    codebook_size
             _UpperCAmelCase     :  Optional[Any]							      =    codebook_dim if codebook_dim is not None else hidden_size
             _UpperCAmelCase     :  Optional[int]							      =    use_conv_shortcut

             if self.norm_type not in ["weight_norm", "time_group_norm"]:
                    raise ValueError(
                        F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}"""       )

             super().__init__(**A       )




      @property
      def      _A	(       self						:				Any       ):
             if self.chunk_length_s is None:
                    return None
             else:
                    return int(self.chunk_length_s * self.sampling_rate       )




      @property
      def      _A	(       self						:				Union[str, Any]       ):
             if self.chunk_length_s is None or self.overlap is None:
                    return None
             else:
                    return max(1						,					int((1.0 - self.overlap) * self.chunk_length       )       )




      @property
      def      _A	(       self						:				Union[str, Any]       ):
             _UpperCAmelCase     :  Dict							      =    np.prod(self.upsampling_ratios       )
             return math.ceil(self.sampling_rate / hop_length       )





      @property
      def      _A	(       self						:				str       ):
             return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10)       )

