




"""simple docstring"""






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

import numpy as np

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


lowercase__  		=		logging.get_logger(__name__)






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    ["""input_values""", """attention_mask"""]
			def __init__(						self						,   lowercase = 1						,   lowercase = 16000						,   lowercase = 0.0						,   lowercase = False						,   lowercase = 80						,   lowercase = 16						,   lowercase = 64						,   lowercase = "hann_window"						,   lowercase = 1.0						,   lowercase = 80						,   lowercase = 7600						,   lowercase = 1E-10						,   lowercase = 2						,   lowercase = True						,   **lowercase						,   ):
							super().__init__(feature_size=lowercase						,   sampling_rate=lowercase						,   padding_value=lowercase						,   **lowercase						)
							_lowerCamelCase  :    List[str]					=					do_normalize
							_lowerCamelCase  :    str					=					return_attention_mask

							_lowerCamelCase  :    Optional[int]					=					num_mel_bins
							_lowerCamelCase  :    List[str]					=					hop_length
							_lowerCamelCase  :    Tuple					=					win_length
							_lowerCamelCase  :    int					=					win_function
							_lowerCamelCase  :    int					=					frame_signal_scale
							_lowerCamelCase  :    Union[str, Any]					=					fmin
							_lowerCamelCase  :    int					=					fmax
							_lowerCamelCase  :    int					=					mel_floor
							_lowerCamelCase  :    Dict					=					reduction_factor

							_lowerCamelCase  :    Any					=					win_length * sampling_rate // 1000
							_lowerCamelCase  :    List[str]					=					hop_length * sampling_rate // 1000
							_lowerCamelCase  :    Any					=					optimal_fft_length(self.sample_size						)
							_lowerCamelCase  :    str					=					(self.n_fft // 2) + 1

							_lowerCamelCase  :    Union[str, Any]					=					window_function(window_length=self.sample_size						,   name=self.win_function						,   periodic=lowercase						)

							_lowerCamelCase  :    Optional[int]					=					mel_filter_bank(
							    num_frequency_bins=self.n_freqs						,   num_mel_filters=self.num_mel_bins						,   min_frequency=self.fmin						,   max_frequency=self.fmax						,   sampling_rate=self.sampling_rate						,   norm='slaney'						,   mel_scale='slaney'						,   )

							if frame_signal_scale != 1.0:
											warnings.warn(
											    'The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers'						,   lowercase						,   )
							if reduction_factor != 2.0:
											warnings.warn(
											    'The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers'						,   lowercase						,   )
			@staticmethod
			# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
			def       A_					(						lowercase						,   lowercase						,   lowercase = 0.0						):
							if attention_mask is not None:
											_lowerCamelCase  :    List[Any]					=					np.array(lowercase						,   np.intaa						)
											_lowerCamelCase  :    int					=					[]

											for vector, length in zip(lowercase						,   attention_mask.sum(-1						)						):
															_lowerCamelCase  :    Union[str, Any]					=					(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7						)
															if length < normed_slice.shape[0]:
																			_lowerCamelCase  :    Optional[Any]					=					padding_value

															normed_input_values.append(lowercase						)
							else:
											_lowerCamelCase  :    Dict					=					[(x - x.mean()) / np.sqrt(x.var() + 1E-7						) for x in input_values]

							return normed_input_values
			def       A_					(						self						,   lowercase						,   ):
							_lowerCamelCase  :    Dict					=					spectrogram(
							    lowercase						,   window=self.window						,   frame_length=self.sample_size						,   hop_length=self.sample_stride						,   fft_length=self.n_fft						,   mel_filters=self.mel_filters						,   mel_floor=self.mel_floor						,   log_mel='log10'						,   )
							return log_mel_spec.T
			def __call__(						self						,   lowercase = None						,   lowercase = None						,   lowercase = False						,   lowercase = None						,   lowercase = False						,   lowercase = None						,   lowercase = None						,   lowercase = None						,   lowercase = None						,   **lowercase						,   ):
							if audio is None and audio_target is None:
											raise ValueError('You must provide either `audio` or `audio_target` values.'						)

							if sampling_rate is not None:
											if sampling_rate != self.sampling_rate:
															raise ValueError(
															    F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
															    F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'''
															    F''' {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.'						)

							if audio is not None:
											_lowerCamelCase  :    Tuple					=					self._process_audio(
											    lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   **lowercase						,   )
							else:
											_lowerCamelCase  :    List[Any]					=					None

							if audio_target is not None:
											_lowerCamelCase  :    Any					=					self._process_audio(
											    lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   **lowercase						,   )

											if inputs is None:
															return inputs_target
											else:
															_lowerCamelCase  :    Tuple					=					inputs_target['input_values']
															_lowerCamelCase  :    Union[str, Any]					=					inputs_target.get('attention_mask'						)
															if decoder_attention_mask is not None:
																			_lowerCamelCase  :    Tuple					=					decoder_attention_mask

							return inputs
			def       A_					(						self						,   lowercase						,   lowercase = False						,   lowercase = False						,   lowercase = None						,   lowercase = False						,   lowercase = None						,   lowercase = None						,   lowercase = None						,   **lowercase						,   ):
							_lowerCamelCase  :    str					=					isinstance(lowercase						,   np.ndarray						) and len(speech.shape						) > 1
							if is_batched_numpy and len(speech.shape						) > 2:
											raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''						)
							_lowerCamelCase  :    Any					=					is_batched_numpy or (
							    isinstance(lowercase						,   (list, tuple)						) and (isinstance(speech[0]						,   (np.ndarray, tuple, list)						))
							)

							if is_batched:
											_lowerCamelCase  :    Dict					=					[np.asarray(lowercase						,   dtype=np.floataa						) for speech in speech]
							elif not is_batched and not isinstance(lowercase						,   np.ndarray						):
											_lowerCamelCase  :    Optional[int]					=					np.asarray(lowercase						,   dtype=np.floataa						)
							elif isinstance(lowercase						,   np.ndarray						) and speech.dtype is np.dtype(np.floataa						):
											_lowerCamelCase  :    Dict					=					speech.astype(np.floataa						)

							# always return batch
							if not is_batched:
											_lowerCamelCase  :    str					=					[speech]

							# needed to make pad() work on spectrogram inputs
							_lowerCamelCase  :    str					=					self.feature_size

							# convert into correct format for padding
							if is_target:
											_lowerCamelCase  :    Union[str, Any]					=					[self._extract_mel_features(lowercase						) for waveform in speech]
											_lowerCamelCase  :    str					=					BatchFeature({'input_values': features}						)
											_lowerCamelCase  :    List[str]					=					self.num_mel_bins
							else:
											_lowerCamelCase  :    Tuple					=					BatchFeature({'input_values': speech}						)

							_lowerCamelCase  :    Union[str, Any]					=					self.pad(
							    lowercase						,   padding=lowercase						,   max_length=lowercase						,   truncation=lowercase						,   pad_to_multiple_of=lowercase						,   return_attention_mask=lowercase						,   **lowercase						,   )

							_lowerCamelCase  :    List[Any]					=					feature_size_hack

							# convert input values to correct format
							_lowerCamelCase  :    str					=					padded_inputs['input_values']
							if not isinstance(input_values[0]						,   np.ndarray						):
											_lowerCamelCase  :    Optional[Any]					=					[np.asarray(lowercase						,   dtype=np.floataa						) for array in input_values]
							elif (
							    not isinstance(lowercase						,   np.ndarray						)
							    and isinstance(input_values[0]						,   np.ndarray						)
							    and input_values[0].dtype is np.dtype(np.floataa						)
							):
											_lowerCamelCase  :    List[Any]					=					[array.astype(np.floataa						) for array in input_values]
							elif isinstance(lowercase						,   np.ndarray						) and input_values.dtype is np.dtype(np.floataa						):
											_lowerCamelCase  :    Tuple					=					input_values.astype(np.floataa						)

							# convert attention_mask to correct format
							_lowerCamelCase  :    Tuple					=					padded_inputs.get('attention_mask'						)
							if attention_mask is not None:
											_lowerCamelCase  :    Any					=					[np.asarray(lowercase						,   dtype=np.intaa						) for array in attention_mask]

							# zero-mean and unit-variance normalization
							if not is_target and self.do_normalize:
											_lowerCamelCase  :    List[Any]					=					(
											    attention_mask
											    if self._get_padding_strategies(lowercase						,   max_length=lowercase						) is not PaddingStrategy.DO_NOT_PAD
											    else None
											)
											_lowerCamelCase  :    Any					=					self.zero_mean_unit_var_norm(
											    padded_inputs['input_values']						,   attention_mask=lowercase						,   padding_value=self.padding_value						)

							if return_tensors is not None:
											_lowerCamelCase  :    int					=					padded_inputs.convert_to_tensors(lowercase						)

							return padded_inputs






			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					super().to_dict()

							# Don't serialize these as they are derived from the other properties.
							_lowerCamelCase  :    str					=					['window', 'mel_filters', 'sample_size', 'sample_stride', 'n_fft', 'n_freqs']
							for name in names:
											if name in output:
															del output[name]

							return output





"""simple docstring"""






from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import torch

from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available






@dataclass
class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    42


try:
			if not (is_transformers_available() and is_torch_available()):
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
			from .pipeline_text_to_video_synth import TextToVideoSDPipeline
			from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline  # noqa: F401
			from .pipeline_text_to_video_zero import TextToVideoZeroPipeline