
"""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       __magic_name__							:
       def __init__(  self			,					A_			,					A_=3			,					A_=32			,					A_=3			,					A_=10			,					A_=[10, 20, 30, 40]			,					A_=[1, 1, 2, 1]			,					A_=True			,					A_=True			,					A_="relu"			,					A_=3			,					A_=None			,					)  ->						Any:





         """simple docstring"""




         _lowercase:      Dict   			=  parent
         _lowercase:      Union[str, Any]   			=  batch_size
         _lowercase:      Tuple   			=  image_size
         _lowercase:      Optional[Any]   			=  num_channels
         _lowercase:      Union[str, Any]   			=  embeddings_size
         _lowercase:      Any   			=  hidden_sizes
         _lowercase:      Dict   			=  depths
         _lowercase:      Union[str, Any]   			=  is_training
         _lowercase:      Dict   			=  use_labels
         _lowercase:      Optional[Any]   			=  hidden_act
         _lowercase:      Dict   			=  num_labels
         _lowercase:      Any   			=  scope
         _lowercase:      Optional[Any]   			=  len(A_							)
       def 				lowercase_				(  self							)  ->						int:





         """simple docstring"""




         _lowercase:      Union[str, Any]   			=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

         _lowercase:      List[Any]   			=  self.get_config()
         return config, pixel_values, labels
       def 				lowercase_				(  self							)  ->						Union[str, Any]:





         """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 				lowercase_				(  self			,					A_			,					A_			,					A_							)  ->						Dict:





         """simple docstring"""




         _lowercase:      Union[str, Any]   			=  TFRegNetModel(config=A_							)
         _lowercase:      Union[str, Any]   			=  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 				lowercase_				(  self			,					A_			,					A_			,					A_							)  ->						Optional[Any]:





         """simple docstring"""




         _lowercase:      Optional[Any]   			=  self.num_labels
         _lowercase:      Tuple   			=  TFRegNetForImageClassification(A_							)
         _lowercase:      Any   			=  model(A_			,					labels=A_			,					training=A_							)
         self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_labels)							)



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





         """simple docstring"""




         _lowercase:      Union[str, Any]   			=  self.prepare_config_and_inputs()
         _lowercase			,					_lowercase			,					_lowercase:      Dict   			=  config_and_inputs
         _lowercase:      Tuple   			=  {'''pixel_values''': pixel_values}
         return config, inputs_dict


@require_tf
class       __magic_name__							(							SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__ ,       unittest.TestCase			):
       UpperCamelCase_ =		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
       UpperCamelCase_ =		(
           {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
           if is_tf_available()
           else {}
       )

       UpperCamelCase_ =		False
       UpperCamelCase_ =		False
       UpperCamelCase_ =		False
       UpperCamelCase_ =		False
       UpperCamelCase_ =		False
       def 				lowercase_				(  self							)  ->						Optional[int]:





         """simple docstring"""




         _lowercase:      Any   			=  TFRegNetModelTester(self							)
         _lowercase:      Optional[int]   			=  ConfigTester(self			,					config_class=A_			,					has_text_modality=A_							)
       def 				lowercase_				(  self							)  ->						Optional[int]:





         """simple docstring"""




         return
       @unittest.skip(reason='''RegNet does not use inputs_embeds'''							)
       def 				lowercase_				(  self							)  ->						Optional[Any]:





         """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 				lowercase_				(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         super().test_keras_fit()
       @unittest.skip(reason='''RegNet does not support input and output embeddings'''							)
       def 				lowercase_				(  self							)  ->						List[str]:





         """simple docstring"""




         pass
       def 				lowercase_				(  self							)  ->						str:





         """simple docstring"""




         _lowercase			,					_lowercase:      List[str]   			=  self.model_tester.prepare_config_and_inputs_for_common()

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

           _lowercase:      Optional[int]   			=  ['''pixel_values''']
           self.assertListEqual(arg_names[:1]			,					A_							)
       def 				lowercase_				(  self							)  ->						Optional[int]:





         """simple docstring"""




         _lowercase:      Tuple   			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A_							)
       def 				lowercase_				(  self							)  ->						str:





         """simple docstring"""




         def check_hidden_states_output(A_			,					A_			,					A_							):
           _lowercase:      Dict   			=  model_class(A_							)
           _lowercase:      str   			=  model(**self._prepare_for_class(A_			,					A_							)			,					training=A_							)

           _lowercase:      str   			=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           _lowercase:      Optional[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]			,					)

         _lowercase			,					_lowercase:      Union[str, Any]   			=  self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase:      Tuple   			=  ['''basic''', '''bottleneck''']
         for model_class in self.all_model_classes:
           for layer_type in layers_type:
             _lowercase:      Dict   			=  layer_type
             _lowercase:      Tuple   			=  True
             check_hidden_states_output(A_			,					A_			,					A_							)

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

             check_hidden_states_output(A_			,					A_			,					A_							)
       def 				lowercase_				(  self							)  ->						str:





         """simple docstring"""




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

         def check_equivalence(A_			,					A_			,					A_			,					A_={}							):
           _lowercase:      int   			=  model(A_			,					return_dict=A_			,					**A_							)
           _lowercase:      Any   			=  model(A_			,					return_dict=A_			,					**A_							).to_tuple()

           def recursive_check(A_			,					A_							):
             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:
           _lowercase:      Union[str, Any]   			=  model_class(A_							)

           _lowercase:      Tuple   			=  self._prepare_for_class(A_			,					A_							)
           _lowercase:      Dict   			=  self._prepare_for_class(A_			,					A_							)
           check_equivalence(A_			,					A_			,					A_							)

           _lowercase:      Dict   			=  self._prepare_for_class(A_			,					A_			,					return_labels=A_							)
           _lowercase:      Dict   			=  self._prepare_for_class(A_			,					A_			,					return_labels=A_							)
           check_equivalence(A_			,					A_			,					A_							)

           _lowercase:      int   			=  self._prepare_for_class(A_			,					A_							)
           _lowercase:      Tuple   			=  self._prepare_for_class(A_			,					A_							)
           check_equivalence(A_			,					A_			,					A_			,					{'''output_hidden_states''': True}							)

           _lowercase:      Union[str, Any]   			=  self._prepare_for_class(A_			,					A_			,					return_labels=A_							)
           _lowercase:      str   			=  self._prepare_for_class(A_			,					A_			,					return_labels=A_							)
           check_equivalence(A_			,					A_			,					A_			,					{'''output_hidden_states''': True}							)
       def 				lowercase_				(  self							)  ->						int:





         """simple docstring"""




         _lowercase:      Optional[int]   			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*A_							)



       @slow
       def 				lowercase_				(  self							)  ->						Any:





         """simple docstring"""




         for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase:      int   			=  TFRegNetModel.from_pretrained(A_							)
           self.assertIsNotNone(A_							)




def 			_lowerCAmelCase		(		):






  """simple docstring"""



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







@require_tf
@require_vision
class       __magic_name__							(							unittest.TestCase			):
       @cached_property
       def 				lowercase_				(  self							)  ->						List[str]:





         """simple docstring"""




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



       @slow
       def 				lowercase_				(  self							)  ->						List[Any]:





         """simple docstring"""




         _lowercase:      Dict   			=  TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

         _lowercase:      Optional[int]   			=  self.default_image_processor
         _lowercase:      Optional[Any]   			=  prepare_img()
         _lowercase:      List[str]   			=  image_processor(images=A_			,					return_tensors='''tf'''							)

         # forward pass
         _lowercase:      Tuple   			=  model(**A_			,					training=A_							)

         # verify the logits
         _lowercase:      Optional[Any]   			=  tf.TensorShape((1, 1000)							)
         self.assertEqual(outputs.logits.shape			,					A_							)

         _lowercase:      str   			=  tf.constant([-0.41_80, -1.50_51, -3.48_36]							)

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


"""simple docstring"""




# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool


if is_datasets_available():
  from datasets import load_dataset


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''microsoft/speecht5_tts'''
       UpperCamelCase_ =		(
           '''This is a tool that reads an English text out loud. It takes an input named `text` which should contain the '''
           '''text to read (in English) and returns a waveform object containing the sound.'''
       )
       UpperCamelCase_ =		'''text_reader'''
       UpperCamelCase_ =		SpeechTaProcessor
       UpperCamelCase_ =		SpeechTaForTextToSpeech
       UpperCamelCase_ =		SpeechTaHifiGan

       UpperCamelCase_ =		['''text''']
       UpperCamelCase_ =		['''audio''']
       def 				lowercase_				(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         if self.post_processor is None:
           _lowercase:      Tuple   			=  '''microsoft/speecht5_hifigan'''
         super().setup()
       def 				lowercase_				(  self			,					A_			,					A_=None							)  ->						Optional[int]:





         """simple docstring"""




         _lowercase:      Dict   			=  self.pre_processor(text=A_			,					return_tensors='''pt'''			,					truncation=A_							)

         if speaker_embeddings is None:
           if not is_datasets_available():
             raise ImportError('''Datasets needs to be installed if not passing speaker embeddings.'''							)

           _lowercase:      Union[str, Any]   			=  load_dataset('''Matthijs/cmu-arctic-xvectors'''			,					split='''validation'''							)
           _lowercase:      Optional[int]   			=  torch.tensor(embeddings_dataset[7305]['''xvector''']							).unsqueeze(0							)

         return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}
       def 				lowercase_				(  self			,					A_							)  ->						Optional[int]:





         """simple docstring"""




         with torch.no_grad():
           return self.model.generate_speech(**A_							)



       def 				lowercase_				(  self			,					A_							)  ->						Dict:





         """simple docstring"""




         with torch.no_grad():
           return self.post_processor(A_							).cpu().detach()
