

'''simple docstring'''







import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowerCamelCase									=     logging.get_logger(__name__)


class        A__   (   _snake_case      ):
    lowercase						       =		["input_features"]



    def __init__(       self		,					UpperCamelCase__=80		,					UpperCamelCase__=16000		,					UpperCamelCase__=160		,					UpperCamelCase__=30		,					UpperCamelCase__=400		,					UpperCamelCase__=0.0		,					UpperCamelCase__=False		,					**UpperCamelCase__		,					)    ->   List[str]:





           '''simple docstring'''
           super().__init__(
               feature_size=UpperCamelCase__		,					sampling_rate=UpperCamelCase__		,					padding_value=UpperCamelCase__		,					return_attention_mask=UpperCamelCase__		,					**UpperCamelCase__		,					)
           A_						       =   n_fft
           A_						       =   hop_length
           A_						       =   chunk_length
           A_						       =   chunk_length * sampling_rate
           A_						       =   self.n_samples // hop_length
           A_						       =   sampling_rate
           A_						       =   mel_filter_bank(
               num_frequency_bins=1 + n_fft // 2		,					num_mel_filters=UpperCamelCase__		,					min_frequency=0.0		,					max_frequency=8000.0		,					sampling_rate=UpperCamelCase__		,					norm="""slaney"""		,					mel_scale="""slaney"""		,					)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   np.ndarray:





           '''simple docstring'''
           A_						       =   spectrogram(
               UpperCamelCase__		,					window_function(self.n_fft		,					"""hann"""							)		,					frame_length=self.n_fft		,					hop_length=self.hop_length		,					power=2.0		,					mel_filters=self.mel_filters		,					log_mel="""log10"""		,					)
           A_						       =   log_spec[:, :-1]
           A_						       =   np.maximum(UpperCamelCase__		,					log_spec.max() - 8.0							)
           A_						       =   (log_spec + 4.0) / 4.0
           return log_spec



    @staticmethod
    # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
    def        snake_case_      (       UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__ = 0.0							)    ->   List[np.ndarray]:





           '''simple docstring'''
           if attention_mask is not None:
                  A_						       =   np.array(UpperCamelCase__		,					np.intaa							)
                  A_						       =   []

                  for vector, length in zip(UpperCamelCase__		,					attention_mask.sum(-1							)							):
                         A_						       =   (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7							)
                         if length < normed_slice.shape[0]:
                                A_						       =   padding_value

                         normed_input_values.append(UpperCamelCase__							)
           else:
                  A_						       =   [(x - x.mean()) / np.sqrt(x.var() + 1e-7							) for x in input_values]

           return normed_input_values



    def __call__(       self		,					UpperCamelCase__		,					UpperCamelCase__ = True		,					UpperCamelCase__ = None		,					UpperCamelCase__ = None		,					UpperCamelCase__ = None		,					UpperCamelCase__ = "max_length"		,					UpperCamelCase__ = None		,					UpperCamelCase__ = None		,					UpperCamelCase__ = None		,					**UpperCamelCase__		,					)    ->   BatchFeature:





           '''simple docstring'''

           if sampling_rate is not None:
                  if sampling_rate != self.sampling_rate:
                         raise ValueError(
                             f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
                             f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
                             f''' was sampled with {self.sampling_rate} and not {sampling_rate}.'''							)
           else:
                  logger.warning(
                      """It is strongly recommended to pass the `sampling_rate` argument to this function. """
                      """Failing to do so can result in silent errors that might be hard to debug."""							)

           A_						       =   isinstance(UpperCamelCase__		,					np.ndarray							) and len(raw_speech.shape							) > 1
           if is_batched_numpy and len(raw_speech.shape							) > 2:
                  raise ValueError(f'''Only mono-channel audio is supported for input to {self}'''							)
           A_						       =   is_batched_numpy or (
               isinstance(UpperCamelCase__		,					(list, tuple)							) and (isinstance(raw_speech[0]		,					(np.ndarray, tuple, list)							))
           )

           if is_batched:
                  A_						       =   [np.asarray([speech]		,					dtype=np.floataa							).T for speech in raw_speech]
           elif not is_batched and not isinstance(UpperCamelCase__		,					np.ndarray							):
                  A_						       =   np.asarray(UpperCamelCase__		,					dtype=np.floataa							)
           elif isinstance(UpperCamelCase__		,					np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
                  A_						       =   raw_speech.astype(np.floataa							)

           # always return batch
           if not is_batched:
                  A_						       =   [np.asarray([raw_speech]							).T]

           A_						       =   BatchFeature({"""input_features""": raw_speech}							)

           # convert into correct format for padding

           A_						       =   self.pad(
               UpperCamelCase__		,					padding=UpperCamelCase__		,					max_length=max_length if max_length else self.n_samples		,					truncation=UpperCamelCase__		,					pad_to_multiple_of=UpperCamelCase__		,					return_attention_mask=return_attention_mask or do_normalize		,					)

           # zero-mean and unit-variance normalization
           if do_normalize:
                  A_						       =   self.zero_mean_unit_var_norm(
                      padded_inputs["""input_features"""]		,					attention_mask=padded_inputs["""attention_mask"""]		,					padding_value=self.padding_value		,					)
                  A_						       =   np.stack(padded_inputs["""input_features"""]		,					axis=0							)

           # make sure list is in array format
           A_						       =   padded_inputs.get("""input_features"""							).transpose(2		,					0		,					1							)

           A_						       =   [self._np_extract_fbank_features(UpperCamelCase__							) for waveform in input_features[0]]

           if isinstance(input_features[0]		,					UpperCamelCase__							):
                  A_						       =   [np.asarray(UpperCamelCase__		,					dtype=np.floataa							) for feature in input_features]
           else:
                  A_						       =   input_features

           if return_attention_mask:
                  # rescale from sample (48000) to feature (3000)
                  A_						       =   padded_inputs["""attention_mask"""][:, :: self.hop_length]

           if return_tensors is not None:
                  A_						       =   padded_inputs.convert_to_tensors(UpperCamelCase__							)

           return padded_inputs







    def        snake_case_      (       self							)    ->   Dict[str, Any]:





           '''simple docstring'''
           A_						       =   copy.deepcopy(self.__dict__							)
           A_						       =   self.__class__.__name__
           if "mel_filters" in output:
                  del output["mel_filters"]
           return output



'''simple docstring'''







from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
      import tensorflow as tf

      from transformers import TFBlipTextModel
      from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class        A__   :



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=12		,					UpperCamelCase__=7		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=99		,					UpperCamelCase__=32		,					UpperCamelCase__=32		,					UpperCamelCase__=2		,					UpperCamelCase__=4		,					UpperCamelCase__=37		,					UpperCamelCase__=0.1		,					UpperCamelCase__=0.1		,					UpperCamelCase__=512		,					UpperCamelCase__=0.02		,					UpperCamelCase__=0		,					UpperCamelCase__=None		,					)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   seq_length
           A_						       =   is_training
           A_						       =   use_input_mask
           A_						       =   use_labels
           A_						       =   vocab_size
           A_						       =   hidden_size
           A_						       =   projection_dim
           A_						       =   num_hidden_layers
           A_						       =   num_attention_heads
           A_						       =   intermediate_size
           A_						       =   dropout
           A_						       =   attention_dropout
           A_						       =   max_position_embeddings
           A_						       =   initializer_range
           A_						       =   scope
           A_						       =   bos_token_id



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

           A_						       =   None
           if self.use_input_mask:
                  A_						       =   random_attention_mask([self.batch_size, self.seq_length]							)

           if input_mask is not None:
                  A_						       =   input_mask.numpy()
                  A_       ,      A_						       =   input_mask.shape
                  A_						       =   np.random.randint(1		,					seq_length - 1		,					size=(batch_size,)							)
                  for batch_idx, start_index in enumerate(UpperCamelCase__							):
                         A_						       =   1
                         A_						       =   0

           A_						       =   self.get_config()

           return config, input_ids, tf.convert_to_tensor(UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           return BlipTextConfig(
               vocab_size=self.vocab_size		,					hidden_size=self.hidden_size		,					projection_dim=self.projection_dim		,					num_hidden_layers=self.num_hidden_layers		,					num_attention_heads=self.num_attention_heads		,					intermediate_size=self.intermediate_size		,					dropout=self.dropout		,					attention_dropout=self.attention_dropout		,					max_position_embeddings=self.max_position_embeddings		,					initializer_range=self.initializer_range		,					bos_token_id=self.bos_token_id		,					)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           A_						       =   TFBlipTextModel(config=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					training=UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__		,					training=UpperCamelCase__							)
           self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)							)
           self.parent.assertEqual(result.pooler_output.shape		,					(self.batch_size, self.hidden_size)							)







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





           '''simple docstring'''
           A_						       =   self.prepare_config_and_inputs()
           A_       ,      A_       ,      A_						       =   config_and_inputs
           A_						       =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict


@require_tf
class        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		(TFBlipTextModel,) if is_tf_available() else ()
    lowercase						       =		False
    lowercase						       =		False
    lowercase						       =		False



    def        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   BlipTextModelTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase__		,					hidden_size=37							)



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           self.config_tester.run_common_tests()



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__							)



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





           '''simple docstring'''
           pass



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





           '''simple docstring'''
           pass



    @unittest.skip(reason="""Blip does not use inputs_embeds"""							)
    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""							)
    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           pass



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





           '''simple docstring'''
           for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A_						       =   TFBlipTextModel.from_pretrained(UpperCamelCase__							)
                  self.assertIsNotNone(UpperCamelCase__							)







    def        snake_case_      (       self		,					UpperCamelCase__=True							)    ->   str:





           '''simple docstring'''
           super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__							)
