




'''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 	SCREAMING_SNAKE_CASE	:




       def __init__(					self      : int	,    A__      : Union[str, Any]	,    A__      : Union[str, Any]=3	,    A__      : int=32	,    A__      : Any=3	,    A__      : List[str]=10	,    A__      : int=[10, 20, 30, 40]	,    A__      : List[str]=[1, 1, 2, 1]	,    A__      : str=True	,    A__      : List[str]=True	,    A__      : Dict="relu"	,    A__      : int=3	,    A__      : Dict=None	,    ):


            """simple docstring"""







            __lowerCamelCase						:       str				   =				parent
            __lowerCamelCase						:       List[Any]				   =				batch_size
            __lowerCamelCase						:       Dict				   =				image_size
            __lowerCamelCase						:       Union[str, Any]				   =				num_channels
            __lowerCamelCase						:       List[str]				   =				embeddings_size
            __lowerCamelCase						:       Optional[Any]				   =				hidden_sizes
            __lowerCamelCase						:       Optional[Any]				   =				depths
            __lowerCamelCase						:       int				   =				is_training
            __lowerCamelCase						:       Tuple				   =				use_labels
            __lowerCamelCase						:       Dict				   =				hidden_act
            __lowerCamelCase						:       List[Any]				   =				num_labels
            __lowerCamelCase						:       Dict				   =				scope
            __lowerCamelCase						:       str				   =				len(__UpperCamelCase					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

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




       def 					a_					(					self      : str					):


            """simple docstring"""







            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__      : int	,    A__      : Tuple	,    A__      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Union[str, Any]				   =				TFRegNetModel(config=__UpperCamelCase					)
            __lowerCamelCase						:       Optional[Any]				   =				model(__UpperCamelCase	,    training=__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 					a_					(					self      : Union[str, Any]	,    A__      : int	,    A__      : List[Any]	,    A__      : List[str]					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				self.num_labels
            __lowerCamelCase						:       int				   =				TFRegNetForImageClassification(__UpperCamelCase					)
            __lowerCamelCase						:       Union[str, Any]				   =				model(__UpperCamelCase	,    labels=__UpperCamelCase	,    training=__UpperCamelCase					)
            self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)					)




       def 					a_					(					self      : int					):


            """simple docstring"""







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







@require_tf
class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_    ,   lowerCAmelCase_    ,   unittest.TestCase  ):
       snake_case__    :     Tuple   		=			(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
       snake_case__    :     Optional[Any]   		=			(
           {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
           if is_tf_available()
           else {}
       )

       snake_case__    :     Union[str, Any]   		=			False
       snake_case__    :     Any   		=			False
       snake_case__    :     Any   		=			False
       snake_case__    :     List[str]   		=			False
       snake_case__    :     Optional[int]   		=			False




       def 					a_					(					self      : Tuple					):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				TFRegNetModelTester(self					)
            __lowerCamelCase						:       Tuple				   =				ConfigTester(self	,    config_class=__UpperCamelCase	,    has_text_modality=__UpperCamelCase					)




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            return




       @unittest.skip(reason="""RegNet does not use inputs_embeds"""					)
       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            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      : Tuple					):


            """simple docstring"""







            super().test_keras_fit()




       @unittest.skip(reason="""RegNet does not support input and output embeddings"""					)
       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            pass




       def 					a_					(					self      : Dict					):


            """simple docstring"""







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

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

                 __lowerCamelCase						:       Any				   =				["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]	,    __UpperCamelCase					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__UpperCamelCase					)




       def 					a_					(					self      : int					):


            """simple docstring"""







            def check_hidden_states_output(A__      : Union[str, Any]	,    A__      : str	,    A__      : Any					):
                 __lowerCamelCase						:       Union[str, Any]				   =				model_class(__UpperCamelCase					)
                 __lowerCamelCase						:       List[Any]				   =				model(**self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase					)	,    training=__UpperCamelCase					)

                 __lowerCamelCase						:       Union[str, Any]				   =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 __lowerCamelCase						:       List[str]				   =				self.model_tester.num_stages
                 self.assertEqual(len(__UpperCamelCase					)	,    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]	,    )

            __lowerCamelCase   ,      __lowerCamelCase						:       Dict				   =				self.model_tester.prepare_config_and_inputs_for_common()
            __lowerCamelCase						:       Any				   =				["""basic""", """bottleneck"""]
            for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                      __lowerCamelCase						:       Optional[Any]				   =				layer_type
                      __lowerCamelCase						:       int				   =				True
                      check_hidden_states_output(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase					)

                      # check that output_hidden_states also work using config
                      del inputs_dict["output_hidden_states"]
                      __lowerCamelCase						:       List[str]				   =				True

                      check_hidden_states_output(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase					)




       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







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

            def check_equivalence(A__      : List[str]	,    A__      : Optional[Any]	,    A__      : Tuple	,    A__      : List[Any]={}					):
                 __lowerCamelCase						:       str				   =				model(__UpperCamelCase	,    return_dict=__UpperCamelCase	,    **__UpperCamelCase					)
                 __lowerCamelCase						:       Optional[int]				   =				model(__UpperCamelCase	,    return_dict=__UpperCamelCase	,    **__UpperCamelCase					).to_tuple()

                 def recursive_check(A__      : Union[str, Any]	,    A__      : Dict					):
                      if isinstance(__UpperCamelCase	,    (List, Tuple)					):
                           for tuple_iterable_value, dict_iterable_value in zip(__UpperCamelCase	,    __UpperCamelCase					):
                                recursive_check(__UpperCamelCase	,    __UpperCamelCase					)
                      elif tuple_object is None:
                           return
                      else:
                           self.assertTrue(
                               all(tf.equal(__UpperCamelCase	,    __UpperCamelCase					)					)	,    msg=(
                                   """Tuple and dict output are not equal. Difference:"""
                                   f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object					)					)}"
                               )	,    )

                      recursive_check(__UpperCamelCase	,    __UpperCamelCase					)

            for model_class in self.all_model_classes:
                 __lowerCamelCase						:       Any				   =				model_class(__UpperCamelCase					)

                 __lowerCamelCase						:       Union[str, Any]				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase					)
                 __lowerCamelCase						:       Optional[int]				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase					)
                 check_equivalence(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase					)

                 __lowerCamelCase						:       int				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase	,    return_labels=__UpperCamelCase					)
                 __lowerCamelCase						:       Optional[int]				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase	,    return_labels=__UpperCamelCase					)
                 check_equivalence(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase					)

                 __lowerCamelCase						:       int				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase					)
                 __lowerCamelCase						:       Dict				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase					)
                 check_equivalence(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase	,    {"""output_hidden_states""": True}					)

                 __lowerCamelCase						:       int				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase	,    return_labels=__UpperCamelCase					)
                 __lowerCamelCase						:       int				   =				self._prepare_for_class(__UpperCamelCase	,    __UpperCamelCase	,    return_labels=__UpperCamelCase					)
                 check_equivalence(__UpperCamelCase	,    __UpperCamelCase	,    __UpperCamelCase	,    {"""output_hidden_states""": True}					)




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       str				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase					)




       @slow
       def 					a_					(					self      : List[Any]					):


            """simple docstring"""







            for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __lowerCamelCase						:       Dict				   =				TFRegNetModel.from_pretrained(__UpperCamelCase					)
                 self.assertIsNotNone(__UpperCamelCase					)

def     __lowercase  ()   ->     Optional[int]:


     """simple docstring"""
     __lowerCamelCase						:       Dict				   =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
     return image







@require_tf
@require_vision
class 	SCREAMING_SNAKE_CASE	(      unittest.TestCase  ):




       @cached_property
       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            return (
                AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
                if is_vision_available()
                else None
            )




       @slow
       def 					a_					(					self      : List[str]					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

            __lowerCamelCase						:       int				   =				self.default_image_processor
            __lowerCamelCase						:       List[str]				   =				prepare_img()
            __lowerCamelCase						:       Optional[int]				   =				image_processor(images=__UpperCamelCase	,    return_tensors="""tf"""					)

            # forward pass
            __lowerCamelCase						:       List[str]				   =				model(**__UpperCamelCase	,    training=__UpperCamelCase					)

            # verify the logits
            __lowerCamelCase						:       Tuple				   =				tf.TensorShape((1, 1000)					)
            self.assertEqual(outputs.logits.shape	,    __UpperCamelCase					)

            __lowerCamelCase						:       Tuple				   =				tf.constant([-0.4180, -1.5051, -3.4836]					)

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











'''simple docstring'''

from typing import List, Optional, Tuple, Union

import torch

from ...utils import logging, randn_tensor
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline


UpperCAmelCase__						:Dict          =			logging.get_logger(__name__)  # pylint: disable=invalid-name







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):




       def __init__(					self      : int	,    A__      : List[Any]	,    A__      : Tuple					):


            """simple docstring"""







            super().__init__()
            self.register_modules(unet=A__	,    scheduler=A__					)




       @torch.no_grad()
       def __call__(					self      : List[str]	,    A__      : int = 1	,    A__      : int = 100	,    A__      : Optional[Union[torch.Generator, List[torch.Generator]]] = None	,    A__      : Optional[float] = None	,    A__      : bool = True	,    ):


            """simple docstring"""







            if audio_length_in_s is None:
                 __lowerCamelCase						:       Union[str, Any]				   =				self.unet.config.sample_size / self.unet.config.sample_rate

            __lowerCamelCase						:       int				   =				audio_length_in_s * self.unet.config.sample_rate

            __lowerCamelCase						:       List[Any]				   =				2 ** len(self.unet.up_blocks					)
            if sample_size < 3 * down_scale_factor:
                 raise ValueError(
                     f"{audio_length_in_s} is too small. Make sure it's bigger or equal to"
                     f" {3 * down_scale_factor / self.unet.config.sample_rate}."					)

            __lowerCamelCase						:       Any				   =				int(A__					)
            if sample_size % down_scale_factor != 0:
                 __lowerCamelCase						:       Optional[Any]				   =				(
                     (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1
                 ) * down_scale_factor
                 logger.info(
                     f"{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled"
                     f" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising"
                     """ process."""					)
            __lowerCamelCase						:       Dict				   =				int(A__					)

            __lowerCamelCase						:       Optional[int]				   =				next(iter(self.unet.parameters()					)					).dtype
            __lowerCamelCase						:       Optional[Any]				   =				(batch_size, self.unet.config.in_channels, sample_size)
            if isinstance(A__	,    A__					) and len(A__					) != batch_size:
                 raise ValueError(
                     f"You have passed a list of generators of length {len(A__					)}, but requested an effective batch"
                     f" size of {batch_size}. Make sure the batch size matches the length of the generators."					)

            __lowerCamelCase						:       int				   =				randn_tensor(A__	,    generator=A__	,    device=self.device	,    dtype=A__					)

            # set step values
            self.scheduler.set_timesteps(A__	,    device=audio.device					)
            __lowerCamelCase						:       List[Any]				   =				self.scheduler.timesteps.to(A__					)

            for t in self.progress_bar(self.scheduler.timesteps					):
                 # 1. predict noise model_output
                 __lowerCamelCase						:       List[str]				   =				self.unet(A__	,    A__					).sample

                 # 2. compute previous image: x_t -> t_t-1
                 __lowerCamelCase						:       Dict				   =				self.scheduler.step(A__	,    A__	,    A__					).prev_sample

            __lowerCamelCase						:       Optional[int]				   =				audio.clamp(-1	,    1					).float().cpu().numpy()

            __lowerCamelCase						:       int				   =				audio[:, :, :original_sample_size]

            if not return_dict:
                 return (audio,)

            return AudioPipelineOutput(audios=A__					)



