


'''simple docstring'''



from typing import 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 ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


_lowercase    :    List[str]			     =  logging.get_logger(__name__)






class  UpperCamelCase__(     lowerCAmelCase ):
				__magic_name__       :   int							= ["input_features", "attention_mask"]




				def __init__(	self    :				int   ,					lowerCAmelCase    :				List[str]=80   ,					lowerCAmelCase    :				Any=16000   ,					lowerCAmelCase    :				Union[str, Any]=0.0   ,					lowerCAmelCase    :				Any=10   ,					lowerCAmelCase    :				Optional[int]=25   ,					lowerCAmelCase    :				List[Any]="hamming_window"   ,					lowerCAmelCase    :				List[str]=32768.0   ,					lowerCAmelCase    :				Any=0.97   ,					lowerCAmelCase    :				Optional[int]=1.0   ,					lowerCAmelCase    :				List[str]=True   ,					lowerCAmelCase    :				str=True   ,					lowerCAmelCase    :				Dict=False   ,					**lowerCAmelCase    :				Any   ,					)->  List[str]:

										"""simple docstring"""




										super().__init__(feature_size=lowerCAmelCase   ,					sampling_rate=lowerCAmelCase   ,					padding_value=lowerCAmelCase   ,					**lowerCAmelCase   )

										UpperCAmelCase         =			feature_size
										UpperCAmelCase         =			sampling_rate
										UpperCAmelCase         =			padding_value
										UpperCAmelCase         =			hop_length
										UpperCAmelCase         =			win_length
										UpperCAmelCase         =			frame_signal_scale
										UpperCAmelCase         =			preemphasis_coeff
										UpperCAmelCase         =			mel_floor
										UpperCAmelCase         =			normalize_means
										UpperCAmelCase         =			normalize_vars
										UpperCAmelCase         =			win_function
										UpperCAmelCase         =			return_attention_mask

										UpperCAmelCase         =			win_length * sampling_rate // 1000
										UpperCAmelCase         =			hop_length * sampling_rate // 1000

										UpperCAmelCase         =			optimal_fft_length(self.sample_size   )
										UpperCAmelCase         =			(self.n_fft // 2) + 1




				def   a__(	self    :				int   ,					lowerCAmelCase    :				np.array   )->  np.ndarray:

										"""simple docstring"""




										if self.win_function == "hamming_window":
																UpperCAmelCase         =			window_function(window_length=self.sample_size   ,					name=self.win_function   ,					periodic=lowerCAmelCase   )
										else:
																UpperCAmelCase         =			window_function(window_length=self.sample_size   ,					name=self.win_function   )

										UpperCAmelCase         =			mel_filter_bank(
										    num_frequency_bins=self.n_freqs   ,					num_mel_filters=self.feature_size   ,					min_frequency=0.0   ,					max_frequency=self.sampling_rate / 2.0   ,					sampling_rate=self.sampling_rate   ,					)

										UpperCAmelCase         =			spectrogram(
										    one_waveform * self.frame_signal_scale   ,					window=lowerCAmelCase   ,					frame_length=self.sample_size   ,					hop_length=self.sample_stride   ,					fft_length=self.n_fft   ,					center=lowerCAmelCase   ,					preemphasis=self.preemphasis_coeff   ,					mel_filters=lowerCAmelCase   ,					mel_floor=self.mel_floor   ,					log_mel='''log'''   ,					)
										return msfc_features.T




				def   a__(	self    :				List[Any]   ,					lowerCAmelCase    :				Union[str, Any]   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				Union[str, Any]   )->  Tuple:

										"""simple docstring"""




										if self.normalize_means:
																UpperCAmelCase         =			x[:input_length].mean(axis=0   )
																UpperCAmelCase         =			np.subtract(lowerCAmelCase   ,					lowerCAmelCase   )
										if self.normalize_vars:
																UpperCAmelCase         =			x[:input_length].std(axis=0   )
																UpperCAmelCase         =			np.divide(lowerCAmelCase   ,					lowerCAmelCase   )

										if input_length < x.shape[0]:
																UpperCAmelCase         =			padding_value

										# make sure array is in float32
										UpperCAmelCase         =			x.astype(np.floataa   )

										return x




				def   a__(	self    :				Optional[int]   ,					lowerCAmelCase    :				List[np.ndarray]   ,					lowerCAmelCase    :				Optional[np.ndarray] = None   )->  List[np.ndarray]:

										"""simple docstring"""




										UpperCAmelCase         =			attention_mask.sum(-1   ) if attention_mask is not None else [x.shape[0] for x in input_features]
										return [self._normalize_one(lowerCAmelCase   ,					lowerCAmelCase   ,					self.padding_value   ) for x, n in zip(lowerCAmelCase   ,					lowerCAmelCase   )]





				def __call__(	self    :				List[Any]   ,					lowerCAmelCase    :				Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]   ,					lowerCAmelCase    :				Union[bool, str, PaddingStrategy] = False   ,					lowerCAmelCase    :				Optional[int] = None   ,					lowerCAmelCase    :				bool = False   ,					lowerCAmelCase    :				Optional[int] = None   ,					lowerCAmelCase    :				Optional[bool] = None   ,					lowerCAmelCase    :				Optional[Union[str, TensorType]] = None   ,					lowerCAmelCase    :				Optional[int] = None   ,					**lowerCAmelCase    :				Optional[int]   ,					)->  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} was trained using a sampling rate of"""
																						    F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` 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.'''   )

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

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

										# always return batch
										if not is_batched:
																UpperCAmelCase         =			[raw_speech]

										# extract fbank features
										UpperCAmelCase         =			[self._extract_mfsc_features(lowerCAmelCase   ) for one_waveform in raw_speech]

										# convert into correct format for padding
										UpperCAmelCase         =			BatchFeature({'''input_features''': features}   )

										UpperCAmelCase         =			self.pad(
										    lowerCAmelCase   ,					padding=lowerCAmelCase   ,					max_length=lowerCAmelCase   ,					truncation=lowerCAmelCase   ,					pad_to_multiple_of=lowerCAmelCase   ,					return_attention_mask=lowerCAmelCase   ,					**lowerCAmelCase   ,					)
										# make sure list is in array format
										UpperCAmelCase         =			padded_inputs.get('''input_features'''   )
										if isinstance(input_features[0]   ,					lowerCAmelCase   ):
																UpperCAmelCase         =			[np.asarray(lowerCAmelCase   ,					dtype=np.floataa   ) for feature in input_features]

										UpperCAmelCase         =			padded_inputs.get('''attention_mask'''   )
										if attention_mask is not None:
																UpperCAmelCase         =			[np.asarray(lowerCAmelCase   ,					dtype=np.intaa   ) for array in attention_mask]

										if self.normalize_means or self.normalize_vars:
																UpperCAmelCase         =			(
																    np.array(lowerCAmelCase   ,					dtype=np.intaa   )
																    if self._get_padding_strategies(lowerCAmelCase   ,					max_length=lowerCAmelCase   ) is not PaddingStrategy.DO_NOT_PAD
																    and padding
																    else None
																)
																UpperCAmelCase         =			self.normalize(
																    padded_inputs['''input_features''']   ,					attention_mask=lowerCAmelCase   )

										if return_tensors is not None:
																UpperCAmelCase         =			padded_inputs.convert_to_tensors(lowerCAmelCase   )

										return padded_inputs









'''simple docstring'''



import argparse
import os
import re

import packaging.version


_lowercase    :    Optional[int]			     =  """examples/"""
_lowercase    :    str			     =  {
    """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""),
    """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""),
    """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""),
    """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""),
}
_lowercase    :    Dict			     =  {
    """init""": """src/transformers/__init__.py""",
    """setup""": """setup.py""",
}
_lowercase    :    List[Any]			     =  """README.md"""


def    lowerCamelCase__   ( A     :    int   ,     A     :    str   ,     A     :    Optional[Any]  ):




						'''simple docstring'''






						with open(A   ,     '''r'''   ,     encoding='''utf-8'''   ,     newline='''\n'''  ) as f:
												UpperCAmelCase         =			f.read()
						UpperCAmelCase       ,       UpperCAmelCase         =			REPLACE_PATTERNS[pattern]
						UpperCAmelCase         =			replace.replace('''VERSION'''   ,     A  )
						UpperCAmelCase         =			re_pattern.sub(A   ,     A  )
						with open(A   ,     '''w'''   ,     encoding='''utf-8'''   ,     newline='''\n'''  ) as f:
												f.write(A  )


def    lowerCamelCase__   ( A     :    Optional[int]  ):




						'''simple docstring'''






						for folder, directories, fnames in os.walk(A  ):
												# Removing some of the folders with non-actively maintained examples from the walk
												if "research_projects" in directories:
																		directories.remove('''research_projects'''  )
												if "legacy" in directories:
																		directories.remove('''legacy'''  )
												for fname in fnames:
																		if fname.endswith('''.py'''  ):
																								update_version_in_file(os.path.join(A   ,     A  )   ,     A   ,     pattern='''examples'''  )


def    lowerCamelCase__   ( A     :    str   ,     A     :    Dict=False  ):




						'''simple docstring'''






						for pattern, fname in REPLACE_FILES.items():
												update_version_in_file(A   ,     A   ,     A  )
						if not patch:
												update_version_in_examples(A  )


def    lowerCamelCase__   ( ):




						'''simple docstring'''






						UpperCAmelCase         =			'''🤗 Transformers currently provides the following architectures'''
						UpperCAmelCase         =			'''1. Want to contribute a new model?'''
						with open(A   ,     '''r'''   ,     encoding='''utf-8'''   ,     newline='''\n'''  ) as f:
												UpperCAmelCase         =			f.readlines()

						# Find the start of the list.
						UpperCAmelCase         =			0
						while not lines[start_index].startswith(_start_prompt  ):
												start_index += 1
						start_index += 1

						UpperCAmelCase         =			start_index
						# Update the lines in the model list.
						while not lines[index].startswith(_end_prompt  ):
												if lines[index].startswith('''1.'''  ):
																		UpperCAmelCase         =			lines[index].replace(
																		    '''https://huggingface.co/docs/transformers/main/model_doc'''   ,     '''https://huggingface.co/docs/transformers/model_doc'''   ,     )
												index += 1

						with open(A   ,     '''w'''   ,     encoding='''utf-8'''   ,     newline='''\n'''  ) as f:
												f.writelines(A  )


def    lowerCamelCase__   ( ):




						'''simple docstring'''






						with open(REPLACE_FILES['''init''']   ,     '''r'''  ) as f:
												UpperCAmelCase         =			f.read()
						UpperCAmelCase         =			REPLACE_PATTERNS['''init'''][0].search(A  ).groups()[0]
						return packaging.version.parse(A  )


def    lowerCamelCase__   ( A     :    Tuple=False  ):




						'''simple docstring'''






						UpperCAmelCase         =			get_version()
						if patch and default_version.is_devrelease:
												raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!'''  )
						if default_version.is_devrelease:
												UpperCAmelCase         =			default_version.base_version
						elif patch:
												UpperCAmelCase         =			f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
						else:
												UpperCAmelCase         =			f"""{default_version.major}.{default_version.minor + 1}.0"""

						# Now let's ask nicely if that's the right one.
						UpperCAmelCase         =			input(f"""Which version are you releasing? [{default_version}]"""  )
						if len(A  ) == 0:
												UpperCAmelCase         =			default_version

						print(f"""Updating version to {version}."""  )
						global_version_update(A   ,     patch=A  )
						if not patch:
												print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''  )
												clean_main_ref_in_model_list()


def    lowerCamelCase__   ( ):




						'''simple docstring'''






						UpperCAmelCase         =			get_version()
						UpperCAmelCase         =			f"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
						UpperCAmelCase         =			current_version.base_version

						# Check with the user we got that right.
						UpperCAmelCase         =			input(f"""Which version are we developing now? [{dev_version}]"""  )
						if len(A  ) == 0:
												UpperCAmelCase         =			dev_version

						print(f"""Updating version to {version}."""  )
						global_version_update(A  )
						print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''  )
						clean_main_ref_in_model_list()


if __name__ == "__main__":
	_lowercase    :    Optional[Any]			     =  argparse.ArgumentParser()
	parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""")
	parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""")
	_lowercase    :    Union[str, Any]			     =  parser.parse_args()
	if not args.post_release:
		pre_release_work(patch=args.patch)
	elif args.patch:
		print("""Nothing to do after a patch :-)""")
	else:
		post_release_work()





