


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


lowerCAmelCase       =							logging.get_logger(__name__)


class        _a							(			UpperCamelCase__			):
							_lowercase	:			List[str]        = ['''input_features''', '''is_longer''']

							def __init__(							self:	List[str]    ,						UpperCamelCase_:	List[Any]=64    ,						UpperCamelCase_:	str=48_000    ,						UpperCamelCase_:	List[Any]=480    ,						UpperCamelCase_:	Any=10    ,						UpperCamelCase_:	Optional[int]=1_024    ,						UpperCamelCase_:	Tuple=0.0    ,						UpperCamelCase_:	Optional[int]=False    ,						UpperCamelCase_:	float = 0    ,						UpperCamelCase_:	float = 14_000    ,						UpperCamelCase_:	int = None    ,						UpperCamelCase_:	str = "fusion"    ,						UpperCamelCase_:	str = "repeatpad"    ,						**UpperCamelCase_:	int    ,						)			->   List[str]:





									"""simple docstring"""







									super().__init__(
									    feature_size=UpperCamelCase_    ,						sampling_rate=UpperCamelCase_    ,						padding_value=UpperCamelCase_    ,						return_attention_mask=UpperCamelCase_    ,						**UpperCamelCase_    ,						)
									lowercase__            =      top_db
									lowercase__            =      truncation
									lowercase__            =      padding
									lowercase__            =      fft_window_size
									lowercase__            =      (fft_window_size >> 1) + 1
									lowercase__            =      hop_length
									lowercase__            =      max_length_s
									lowercase__            =      max_length_s * sampling_rate
									lowercase__            =      sampling_rate
									lowercase__            =      frequency_min
									lowercase__            =      frequency_max
									lowercase__            =      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'''    ,						)
									lowercase__            =      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       lowerCamelCase_ (							self:	int							)			->   Dict[str, Any]:





									"""simple docstring"""







									lowercase__            =      copy.deepcopy(self.__dict__							)
									lowercase__            =      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       lowerCamelCase_ (							self:	List[str]    ,						UpperCamelCase_:	np.array    ,						UpperCamelCase_:	Optional[np.array] = None							)			->   np.ndarray:





									"""simple docstring"""







									lowercase__            =      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       lowerCamelCase_ (							self:	Optional[int]    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	int    ,						UpperCamelCase_:	Optional[int]							)			->   int:





									"""simple docstring"""







									lowercase__            =      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
											lowercase__            =      [0]
									if len(ranges[2]							) == 0:
											# if the audio is too short, we just use the first chunk
											lowercase__            =      [0]
									# randomly choose index for each part
									lowercase__            =      np.random.choice(ranges[0]							)
									lowercase__            =      np.random.choice(ranges[1]							)
									lowercase__            =      np.random.choice(ranges[2]							)

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

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

							def       lowerCamelCase_ (							self:	Dict    ,						UpperCamelCase_:	np.array    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	int    ,						UpperCamelCase_:	List[Any]							)			->   np.array:





									"""simple docstring"""







									if waveform.shape[0] > max_length:
											if truncation == "rand_trunc":
													lowercase__            =      True
													# random crop to max_length (for compatibility) -> this should be handled by self.pad
													lowercase__            =      len(UpperCamelCase_							) - max_length
													lowercase__            =      np.random.randint(0    ,						overflow + 1							)
													lowercase__            =      waveform[idx : idx + max_length]
													lowercase__            =      self._np_extract_fbank_features(UpperCamelCase_    ,						self.mel_filters_slaney							)[None, :]
											elif truncation == "fusion":
													lowercase__            =      self._np_extract_fbank_features(UpperCamelCase_    ,						self.mel_filters							)
													lowercase__            =      max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
													lowercase__            =      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.
															lowercase__            =      np.stack([mel, mel, mel, mel]    ,						axis=0							)
															lowercase__            =      False
													else:
															lowercase__            =      self._random_mel_fusion(UpperCamelCase_    ,						UpperCamelCase_    ,						UpperCamelCase_							)
															lowercase__            =      True
											else:
													raise NotImplementedError(f'data_truncating {truncation} not implemented'							)

									else:
											lowercase__            =      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":
															lowercase__            =      int(max_length / len(UpperCamelCase_							)							)
															lowercase__            =      np.stack(np.tile(UpperCamelCase_    ,						n_repeat + 1							)							)[:max_length]
													if padding == "repeatpad":
															lowercase__            =      int(max_length / len(UpperCamelCase_							)							)
															lowercase__            =      np.stack(np.tile(UpperCamelCase_    ,						UpperCamelCase_							)							)
													lowercase__            =      np.pad(UpperCamelCase_    ,						(0, max_length - waveform.shape[0])    ,						mode='''constant'''    ,						constant_values=0							)

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

									return input_mel, longer


							def __call__(							self:	Optional[int]    ,						UpperCamelCase_:	Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]    ,						UpperCamelCase_:	str = None    ,						UpperCamelCase_:	Optional[str] = None    ,						UpperCamelCase_:	Optional[int] = None    ,						UpperCamelCase_:	Optional[int] = None    ,						UpperCamelCase_:	Optional[Union[str, TensorType]] = None    ,						**UpperCamelCase_:	Tuple    ,						)			->   BatchFeature:





									"""simple docstring"""







									lowercase__            =      truncation if truncation is not None else self.truncation
									lowercase__            =      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.'''							)

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

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

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

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

									lowercase__            =      []
									lowercase__            =      []
									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
											lowercase__            =      np.random.randint(0    ,						len(UpperCamelCase_							)							)
											lowercase__            =      True

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

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

									lowercase__            =      {'''input_features''': input_mel, '''is_longer''': is_longer}
									lowercase__            =      BatchFeature(UpperCamelCase_							)

									if return_tensors is not None:
											lowercase__            =      input_features.convert_to_tensors(UpperCamelCase_							)

									return input_features






import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
lowerCAmelCase       =							'src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
lowerCAmelCase       =							direct_transformers_import(PATH_TO_TRANSFORMERS)

lowerCAmelCase       =							transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
lowerCAmelCase       =							re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)')


lowerCAmelCase       =							{
    'DecisionTransformerConfig',
    'EncoderDecoderConfig',
    'MusicgenConfig',
    'RagConfig',
    'SpeechEncoderDecoderConfig',
    'TimmBackboneConfig',
    'VisionEncoderDecoderConfig',
    'VisionTextDualEncoderConfig',
    'LlamaConfig',
}
def 			_a (      SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		lowercase__            =      None

		# source code of `config_class`
		lowercase__            =      inspect.getsource(SCREAMING_SNAKE_CASE     )
		lowercase__            =      _re_checkpoint.findall(SCREAMING_SNAKE_CASE     )

		# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
		# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
		for ckpt_name, ckpt_link in checkpoints:
				# allow the link to end with `/`
				if ckpt_link.endswith('''/'''     ):
						lowercase__            =      ckpt_link[:-1]

				# verify the checkpoint name corresponds to the checkpoint link
				lowercase__            =      f'https://huggingface.co/{ckpt_name}'
				if ckpt_link == ckpt_link_from_name:
						lowercase__            =      ckpt_name
						break

		return checkpoint
def 			_a (      ):


		"""simple docstring"""




		lowercase__            =      []

		for config_class in list(CONFIG_MAPPING.values()     ):
				# Skip deprecated models
				if "models.deprecated" in config_class.__module__:
						continue
				lowercase__            =      get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE     )

				lowercase__            =      config_class.__name__
				if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
						configs_without_checkpoint.append(SCREAMING_SNAKE_CASE     )

		if len(SCREAMING_SNAKE_CASE     ) > 0:
				lowercase__            =      '''\n'''.join(sorted(SCREAMING_SNAKE_CASE     )     )
				raise ValueError(f'The following configurations don\'t contain any valid checkpoint:\n{message}'     )


if __name__ == "__main__":
			check_config_docstrings_have_checkpoints()


