






from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TFConvBertForMaskedLM,
					    TFConvBertForMultipleChoice,
					    TFConvBertForQuestionAnswering,
					    TFConvBertForSequenceClassification,
					    TFConvBertForTokenClassification,
					    TFConvBertModel,
					)


class       __SCREAMING_SNAKE_CASE   :






						def __init__(		self       ,  _UpperCamelCase       ,  _UpperCamelCase=13       ,  _UpperCamelCase=7       ,  _UpperCamelCase=True       ,  _UpperCamelCase=True       ,  _UpperCamelCase=True       ,  _UpperCamelCase=True       ,  _UpperCamelCase=99       ,  _UpperCamelCase=32       ,  _UpperCamelCase=2       ,  _UpperCamelCase=4       ,  _UpperCamelCase=37       ,  _UpperCamelCase="gelu"       ,  _UpperCamelCase=0.1       ,  _UpperCamelCase=0.1       ,  _UpperCamelCase=5_12       ,  _UpperCamelCase=16       ,  _UpperCamelCase=2       ,  _UpperCamelCase=0.02       ,  _UpperCamelCase=3       ,  _UpperCamelCase=4       ,  _UpperCamelCase=None       ,  ):






												"""simple docstring"""
												lowerCAmelCase__        =  parent
												lowerCAmelCase__        =  13
												lowerCAmelCase__        =  7
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  99
												lowerCAmelCase__        =  3_84
												lowerCAmelCase__        =  2
												lowerCAmelCase__        =  4
												lowerCAmelCase__        =  37
												lowerCAmelCase__        =  'gelu'
												lowerCAmelCase__        =  0.1
												lowerCAmelCase__        =  0.1
												lowerCAmelCase__        =  5_12
												lowerCAmelCase__        =  16
												lowerCAmelCase__        =  2
												lowerCAmelCase__        =  0.02
												lowerCAmelCase__        =  3
												lowerCAmelCase__        =  4
												lowerCAmelCase__        =  1_28
												lowerCAmelCase__        =  2
												lowerCAmelCase__        =  9
												lowerCAmelCase__        =  1
												lowerCAmelCase__        =  None






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size				)

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

												lowerCAmelCase__        =  None
												if self.use_token_type_ids:
																		lowerCAmelCase__        =  ids_tensor([self.batch_size, self.seq_length]       ,  self.type_vocab_size				)

												lowerCAmelCase__        =  None
												lowerCAmelCase__        =  None
												lowerCAmelCase__        =  None
												if self.use_labels:
																		lowerCAmelCase__        =  ids_tensor([self.batch_size]       ,  self.type_sequence_label_size				)
																		lowerCAmelCase__        =  ids_tensor([self.batch_size, self.seq_length]       ,  self.num_labels				)
																		lowerCAmelCase__        =  ids_tensor([self.batch_size]       ,  self.num_choices				)

												lowerCAmelCase__        =  ConvBertConfig(
												    vocab_size=self.vocab_size       ,  hidden_size=self.hidden_size       ,  num_hidden_layers=self.num_hidden_layers       ,  num_attention_heads=self.num_attention_heads       ,  intermediate_size=self.intermediate_size       ,  hidden_act=self.hidden_act       ,  hidden_dropout_prob=self.hidden_dropout_prob       ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,  max_position_embeddings=self.max_position_embeddings       ,  type_vocab_size=self.type_vocab_size       ,  initializer_range=self.initializer_range       ,  return_dict=_UpperCamelCase       ,  )

												return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertModel(config=_UpperCamelCase				)
												lowerCAmelCase__        =  {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}

												lowerCAmelCase__        =  [input_ids, input_mask]
												lowerCAmelCase__        =  model(_UpperCamelCase				)

												lowerCAmelCase__        =  model(_UpperCamelCase				)

												self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertForMaskedLM(config=_UpperCamelCase				)
												lowerCAmelCase__        =  {
												    'input_ids': input_ids,
												    'attention_mask': input_mask,
												    'token_type_ids': token_type_ids,
												}
												lowerCAmelCase__        =  model(_UpperCamelCase				)
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.num_labels
												lowerCAmelCase__        =  TFConvBertForSequenceClassification(config=_UpperCamelCase				)
												lowerCAmelCase__        =  {
												    'input_ids': input_ids,
												    'attention_mask': input_mask,
												    'token_type_ids': token_type_ids,
												}

												lowerCAmelCase__        =  model(_UpperCamelCase				)
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.num_choices
												lowerCAmelCase__        =  TFConvBertForMultipleChoice(config=_UpperCamelCase				)
												lowerCAmelCase__        =  tf.tile(tf.expand_dims(_UpperCamelCase       ,  1				)       ,  (1, self.num_choices, 1)				)
												lowerCAmelCase__        =  tf.tile(tf.expand_dims(_UpperCamelCase       ,  1				)       ,  (1, self.num_choices, 1)				)
												lowerCAmelCase__        =  tf.tile(tf.expand_dims(_UpperCamelCase       ,  1				)       ,  (1, self.num_choices, 1)				)
												lowerCAmelCase__        =  {
												    'input_ids': multiple_choice_inputs_ids,
												    'attention_mask': multiple_choice_input_mask,
												    'token_type_ids': multiple_choice_token_type_ids,
												}
												lowerCAmelCase__        =  model(_UpperCamelCase				)
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_choices)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.num_labels
												lowerCAmelCase__        =  TFConvBertForTokenClassification(config=_UpperCamelCase				)
												lowerCAmelCase__        =  {
												    'input_ids': input_ids,
												    'attention_mask': input_mask,
												    'token_type_ids': token_type_ids,
												}
												lowerCAmelCase__        =  model(_UpperCamelCase				)
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.num_labels)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertForQuestionAnswering(config=_UpperCamelCase				)
												lowerCAmelCase__        =  {
												    'input_ids': input_ids,
												    'attention_mask': input_mask,
												    'token_type_ids': token_type_ids,
												}

												lowerCAmelCase__        =  model(_UpperCamelCase				)
												self.parent.assertEqual(result.start_logits.shape       ,  (self.batch_size, self.seq_length)				)
												self.parent.assertEqual(result.end_logits.shape       ,  (self.batch_size, self.seq_length)				)







						def  UpperCamelCase__ (		self				):






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




@require_tf
class       __SCREAMING_SNAKE_CASE   (				__lowercase						,   __lowercase						,   unittest.TestCase):
						_SCREAMING_SNAKE_CASE		:    int						=   (
						    (
						        TFConvBertModel,
						        TFConvBertForMaskedLM,
						        TFConvBertForQuestionAnswering,
						        TFConvBertForSequenceClassification,
						        TFConvBertForTokenClassification,
						        TFConvBertForMultipleChoice,
						    )
						    if is_tf_available()
						    else ()
						)
						_SCREAMING_SNAKE_CASE		:    Optional[int]						=   (
						    {
						        '''feature-extraction''': TFConvBertModel,
						        '''fill-mask''': TFConvBertForMaskedLM,
						        '''question-answering''': TFConvBertForQuestionAnswering,
						        '''text-classification''': TFConvBertForSequenceClassification,
						        '''token-classification''': TFConvBertForTokenClassification,
						        '''zero-shot''': TFConvBertForSequenceClassification,
						    }
						    if is_tf_available()
						    else {}
						)
						_SCREAMING_SNAKE_CASE		:    str						=   False
						_SCREAMING_SNAKE_CASE		:    Optional[int]						=   False
						_SCREAMING_SNAKE_CASE		:    str						=   False






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertModelTester(self				)
												lowerCAmelCase__        =  ConfigTester(self       ,  config_class=_UpperCamelCase       ,  hidden_size=37				)






						def  UpperCamelCase__ (		self				):






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






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_multiple_choice(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*_UpperCamelCase				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase				)






						@slow
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__  ,    lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs_for_common()
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  True

												if hasattr(_UpperCamelCase       ,  'use_cache'				):
																		lowerCAmelCase__        =  True

												lowerCAmelCase__        =  getattr(self.model_tester       ,  'encoder_seq_length'       ,  self.model_tester.seq_length				)
												lowerCAmelCase__        =  getattr(self.model_tester       ,  'key_length'       ,  _UpperCamelCase				)

												for model_class in self.all_model_classes:
																		lowerCAmelCase__        =  self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)
																		lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																		lowerCAmelCase__        =  len(model(_UpperCamelCase				)				)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																								model.save_pretrained(_UpperCamelCase       ,  saved_model=_UpperCamelCase				)
																								lowerCAmelCase__        =  os.path.join(_UpperCamelCase       ,  'saved_model'       ,  '1'				)
																								lowerCAmelCase__        =  tf.keras.models.load_model(_UpperCamelCase				)
																								lowerCAmelCase__        =  model(_UpperCamelCase				)

																								if self.is_encoder_decoder:
																														lowerCAmelCase__        =  outputs['encoder_hidden_states']
																														lowerCAmelCase__        =  outputs['encoder_attentions']
																								else:
																														lowerCAmelCase__        =  outputs['hidden_states']
																														lowerCAmelCase__        =  outputs['attentions']

																								self.assertEqual(len(_UpperCamelCase				)       ,  _UpperCamelCase				)

																								lowerCAmelCase__        =  getattr(
																								    self.model_tester       ,  'expected_num_hidden_layers'       ,  self.model_tester.num_hidden_layers + 1				)

																								self.assertEqual(len(_UpperCamelCase				)       ,  _UpperCamelCase				)
																								self.assertListEqual(
																								    list(output_hidden_states[0].shape[-2:]				)       ,  [self.model_tester.seq_length, self.model_tester.hidden_size]       ,  )

																								self.assertEqual(len(_UpperCamelCase				)       ,  self.model_tester.num_hidden_layers				)
																								self.assertListEqual(
																								    list(output_attentions[0].shape[-3:]				)       ,  [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]       ,  )






						@slow
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertModel.from_pretrained('YituTech/conv-bert-base'				)
												self.assertIsNotNone(_UpperCamelCase				)







						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__  ,    lowerCAmelCase__        =  self.model_tester.prepare_config_and_inputs_for_common()
												lowerCAmelCase__        =  True
												lowerCAmelCase__        =  getattr(self.model_tester       ,  'decoder_seq_length'       ,  self.model_tester.seq_length				)
												lowerCAmelCase__        =  getattr(self.model_tester       ,  'encoder_seq_length'       ,  self.model_tester.seq_length				)
												lowerCAmelCase__        =  getattr(self.model_tester       ,  'key_length'       ,  _UpperCamelCase				)
												lowerCAmelCase__        =  getattr(self.model_tester       ,  'key_length'       ,  _UpperCamelCase				)

												def check_decoder_attentions_output(_UpperCamelCase				):
																		lowerCAmelCase__        =  len(_UpperCamelCase				)
																		self.assertEqual(out_len % 2       ,  0				)
																		lowerCAmelCase__        =  outputs.decoder_attentions
																		self.assertEqual(len(_UpperCamelCase				)       ,  self.model_tester.num_hidden_layers				)
																		self.assertListEqual(
																		    list(decoder_attentions[0].shape[-3:]				)       ,  [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length]       ,  )

												def check_encoder_attentions_output(_UpperCamelCase				):
																		lowerCAmelCase__        =  [
																		    t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
																		]
																		self.assertEqual(len(_UpperCamelCase				)       ,  self.model_tester.num_hidden_layers				)
																		self.assertListEqual(
																		    list(attentions[0].shape[-3:]				)       ,  [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]       ,  )

												for model_class in self.all_model_classes:
																		lowerCAmelCase__        =  True
																		lowerCAmelCase__        =  False
																		lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																		lowerCAmelCase__        =  model(self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)				)
																		lowerCAmelCase__        =  len(_UpperCamelCase				)
																		self.assertEqual(config.output_hidden_states       ,  _UpperCamelCase				)
																		check_encoder_attentions_output(_UpperCamelCase				)

																		if self.is_encoder_decoder:
																								lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																								lowerCAmelCase__        =  model(self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)				)
																								self.assertEqual(config.output_hidden_states       ,  _UpperCamelCase				)
																								check_decoder_attentions_output(_UpperCamelCase				)

																		# Check that output attentions can also be changed via the config
																		del inputs_dict["output_attentions"]
																		lowerCAmelCase__        =  True
																		lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																		lowerCAmelCase__        =  model(self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)				)
																		self.assertEqual(config.output_hidden_states       ,  _UpperCamelCase				)
																		check_encoder_attentions_output(_UpperCamelCase				)

																		# Check attention is always last and order is fine
																		lowerCAmelCase__        =  True
																		lowerCAmelCase__        =  True
																		lowerCAmelCase__        =  model_class(_UpperCamelCase				)
																		lowerCAmelCase__        =  model(self._prepare_for_class(_UpperCamelCase       ,  _UpperCamelCase				)				)

																		self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1)       ,  len(_UpperCamelCase				)				)
																		self.assertEqual(model.config.output_hidden_states       ,  _UpperCamelCase				)
																		check_encoder_attentions_output(_UpperCamelCase				)




@require_tf
class       __SCREAMING_SNAKE_CASE   (				unittest.TestCase):






						@slow
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												lowerCAmelCase__        =  TFConvBertModel.from_pretrained('YituTech/conv-bert-base'				)
												lowerCAmelCase__        =  tf.constant([[0, 1, 2, 3, 4, 5]]				)
												lowerCAmelCase__        =  model(_UpperCamelCase				)[0]

												lowerCAmelCase__        =  [1, 6, 7_68]
												self.assertEqual(output.shape       ,  _UpperCamelCase				)

												lowerCAmelCase__        =  tf.constant(
												    [
												        [
												            [-0.03_47_54_93, -0.4_68_60_34, -0.30_63_88_32],
												            [0.22_63_72_48, -0.26_98_86_46, -0.7_42_34_24],
												            [0.10_32_48_68, -0.45_01_35_08, -0.58_28_07_84],
												        ]
												    ]				)
												tf.debugging.assert_near(output[:, :3, :3]       ,  _UpperCamelCase       ,  atol=1E-4				)













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

import numpy as np
import torch

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


__snake_case      :      Any             =       logging.get_logger(__name__)


class       __SCREAMING_SNAKE_CASE   (				__lowercase):
						_SCREAMING_SNAKE_CASE		:    Tuple						=   ['''input_features''', '''is_longer''']






						def __init__(		self       ,  _UpperCamelCase=64       ,  _UpperCamelCase=4_80_00       ,  _UpperCamelCase=4_80       ,  _UpperCamelCase=10       ,  _UpperCamelCase=10_24       ,  _UpperCamelCase=0.0       ,  _UpperCamelCase=False       ,  _UpperCamelCase = 0       ,  _UpperCamelCase = 1_40_00       ,  _UpperCamelCase = None       ,  _UpperCamelCase = "fusion"       ,  _UpperCamelCase = "repeatpad"       ,  **_UpperCamelCase       ,  ):






												"""simple docstring"""
												super().__init__(
												    feature_size=_UpperCamelCase       ,  sampling_rate=_UpperCamelCase       ,  padding_value=_UpperCamelCase       ,  return_attention_mask=_UpperCamelCase       ,  **_UpperCamelCase       ,  )
												lowerCAmelCase__        =  top_db
												lowerCAmelCase__        =  truncation
												lowerCAmelCase__        =  padding
												lowerCAmelCase__        =  fft_window_size
												lowerCAmelCase__        =  (fft_window_size >> 1) + 1
												lowerCAmelCase__        =  hop_length
												lowerCAmelCase__        =  max_length_s
												lowerCAmelCase__        =  max_length_s * sampling_rate
												lowerCAmelCase__        =  sampling_rate
												lowerCAmelCase__        =  frequency_min
												lowerCAmelCase__        =  frequency_max
												lowerCAmelCase__        =  mel_filter_bank(
												    num_frequency_bins=self.nb_frequency_bins       ,  num_mel_filters=_UpperCamelCase       ,  min_frequency=_UpperCamelCase       ,  max_frequency=_UpperCamelCase       ,  sampling_rate=_UpperCamelCase       ,  norm=_UpperCamelCase       ,  mel_scale='htk'       ,  )
												lowerCAmelCase__        =  mel_filter_bank(
												    num_frequency_bins=self.nb_frequency_bins       ,  num_mel_filters=_UpperCamelCase       ,  min_frequency=_UpperCamelCase       ,  max_frequency=_UpperCamelCase       ,  sampling_rate=_UpperCamelCase       ,  norm='slaney'       ,  mel_scale='slaney'       ,  )






						def  UpperCamelCase__ (		self				):






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






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												lowerCAmelCase__        =  spectrogram(
												    _UpperCamelCase       ,  window_function(self.fft_window_size       ,  'hann'				)       ,  frame_length=self.fft_window_size       ,  hop_length=self.hop_length       ,  power=2.0       ,  mel_filters=_UpperCamelCase       ,  log_mel='dB'       ,  )
												return log_mel_spectrogram.T






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  np.array_split(list(range(0       ,  total_frames - chunk_frames + 1				)				)       ,  3				)
												if len(ranges[1]				) == 0:
																		# if the audio is too short, we just use the first chunk
																		lowerCAmelCase__        =  [0]
												if len(ranges[2]				) == 0:
																		# if the audio is too short, we just use the first chunk
																		lowerCAmelCase__        =  [0]
												# randomly choose index for each part
												lowerCAmelCase__        =  np.random.choice(ranges[0]				)
												lowerCAmelCase__        =  np.random.choice(ranges[1]				)
												lowerCAmelCase__        =  np.random.choice(ranges[2]				)

												lowerCAmelCase__        =  mel[idx_front : idx_front + chunk_frames, :]
												lowerCAmelCase__        =  mel[idx_middle : idx_middle + chunk_frames, :]
												lowerCAmelCase__        =  mel[idx_back : idx_back + chunk_frames, :]

												lowerCAmelCase__        =  torch.tensor(mel[None, None, :]				)
												lowerCAmelCase__        =  torch.nn.functional.interpolate(
												    _UpperCamelCase       ,  size=[chunk_frames, 64]       ,  mode='bilinear'       ,  align_corners=_UpperCamelCase				)
												lowerCAmelCase__        =  mel_shrink[0][0].numpy()
												lowerCAmelCase__        =  np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]       ,  axis=0				)
												return mel_fusion






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				):






												"""simple docstring"""
												if waveform.shape[0] > max_length:
																		if truncation == "rand_trunc":
																								lowerCAmelCase__        =  True
																								# random crop to max_length (for compatibility) -> this should be handled by self.pad
																								lowerCAmelCase__        =  len(_UpperCamelCase				) - max_length
																								lowerCAmelCase__        =  np.random.randint(0       ,  overflow + 1				)
																								lowerCAmelCase__        =  waveform[idx : idx + max_length]
																								lowerCAmelCase__        =  self._np_extract_fbank_features(_UpperCamelCase       ,  self.mel_filters_slaney				)[None, :]
																		elif truncation == "fusion":
																								lowerCAmelCase__        =  self._np_extract_fbank_features(_UpperCamelCase       ,  self.mel_filters				)
																								lowerCAmelCase__        =  max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
																								lowerCAmelCase__        =  mel.shape[0]
																								if chunk_frames == total_frames:
																														# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
																														# In this case, we just use the whole audio.
																														lowerCAmelCase__        =  np.stack([mel, mel, mel, mel]       ,  axis=0				)
																														lowerCAmelCase__        =  False
																								else:
																														lowerCAmelCase__        =  self._random_mel_fusion(_UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase				)
																														lowerCAmelCase__        =  True
																		else:
																								raise NotImplementedError(F"data_truncating {truncation} not implemented"				)

												else:
																		lowerCAmelCase__        =  False
																		# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
																		if waveform.shape[0] < max_length:
																								if padding == "repeat":
																														lowerCAmelCase__        =  int(max_length / len(_UpperCamelCase				)				)
																														lowerCAmelCase__        =  np.stack(np.tile(_UpperCamelCase       ,  n_repeat + 1				)				)[:max_length]
																								if padding == "repeatpad":
																														lowerCAmelCase__        =  int(max_length / len(_UpperCamelCase				)				)
																														lowerCAmelCase__        =  np.stack(np.tile(_UpperCamelCase       ,  _UpperCamelCase				)				)
																								lowerCAmelCase__        =  np.pad(_UpperCamelCase       ,  (0, max_length - waveform.shape[0])       ,  mode='constant'       ,  constant_values=0				)

																		if truncation == "fusion":
																								lowerCAmelCase__        =  self._np_extract_fbank_features(_UpperCamelCase       ,  self.mel_filters				)
																								lowerCAmelCase__        =  np.stack([input_mel, input_mel, input_mel, input_mel]       ,  axis=0				)
																		else:
																								lowerCAmelCase__        =  self._np_extract_fbank_features(_UpperCamelCase       ,  self.mel_filters_slaney				)[None, :]

												return input_mel, longer







						def __call__(		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None       ,  _UpperCamelCase = None       ,  _UpperCamelCase = None       ,  _UpperCamelCase = None       ,  _UpperCamelCase = None       ,  **_UpperCamelCase       ,  ):






												"""simple docstring"""
												lowerCAmelCase__        =  truncation if truncation is not None else self.truncation
												lowerCAmelCase__        =  padding if padding else self.padding

												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.'				)

												lowerCAmelCase__        =  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}"				)
												lowerCAmelCase__        =  is_batched_numpy or (
												    isinstance(_UpperCamelCase       ,  (list, tuple)				) and (isinstance(raw_speech[0]       ,  (np.ndarray, tuple, list)				))
												)

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

												# always return batch
												if not is_batched:
																		lowerCAmelCase__        =  [np.asarray(_UpperCamelCase				)]

												# convert to mel spectrogram, truncate and pad if needed.
												lowerCAmelCase__        =  [
												    self._get_input_mel(_UpperCamelCase       ,  max_length if max_length else self.nb_max_samples       ,  _UpperCamelCase       ,  _UpperCamelCase				)
												    for waveform in raw_speech
												]

												lowerCAmelCase__        =  []
												lowerCAmelCase__        =  []
												for mel, longer in padded_inputs:
																		input_mel.append(_UpperCamelCase				)
																		is_longer.append(_UpperCamelCase				)

												if truncation == "fusion" and sum(_UpperCamelCase				) == 0:
																		# if no audio is longer than 10s, then randomly select one audio to be longer
																		lowerCAmelCase__        =  np.random.randint(0       ,  len(_UpperCamelCase				)				)
																		lowerCAmelCase__        =  True

												if isinstance(input_mel[0]       ,  _UpperCamelCase				):
																		lowerCAmelCase__        =  [np.asarray(_UpperCamelCase       ,  dtype=np.floataa				) for feature in input_mel]

												# is_longer is a list of bool
												lowerCAmelCase__        =  [[longer] for longer in is_longer]

												lowerCAmelCase__        =  {'input_features': input_mel, 'is_longer': is_longer}
												lowerCAmelCase__        =  BatchFeature(_UpperCamelCase				)

												if return_tensors is not None:
																		lowerCAmelCase__        =  input_features.convert_to_tensors(_UpperCamelCase				)

												return input_features





