





'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


_SCREAMING_SNAKE_CASE    =			logging.get_logger(__name__)






class 							__lowercase				(					lowerCAmelCase__  ):







	'''simple docstring'''

	a			: Optional[int]      =				["input_values", "attention_mask"]


	def __init__(self   ,_lowerCamelCase=1   ,_lowerCamelCase=16000   ,_lowerCamelCase=128   ,_lowerCamelCase=1024   ,_lowerCamelCase=0.0   ,_lowerCamelCase=True   ,_lowerCamelCase=-4.2_6_7_7_3_9_3   ,_lowerCamelCase=4.5_6_8_9_9_7_4   ,_lowerCamelCase=False   ,**_lowerCamelCase   ,)							->							Optional[int]:







				'''simple docstring'''





				super().__init__(feature_size=_lowerCamelCase   ,sampling_rate=_lowerCamelCase   ,padding_value=_lowerCamelCase   ,**_lowerCamelCase       )
				__lowercase   =							num_mel_bins
				__lowercase   =							max_length
				__lowercase   =							do_normalize
				__lowercase   =							mean
				__lowercase   =							std
				__lowercase   =							return_attention_mask


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,)							->							np.ndarray:







				'''simple docstring'''





				__lowercase   =							torch.from_numpy(_lowerCamelCase       ).unsqueeze(0       )
				__lowercase   =							ta_kaldi.fbank(
				    _lowerCamelCase   ,htk_compat=_lowerCamelCase   ,sample_frequency=self.sampling_rate   ,use_energy=_lowerCamelCase   ,window_type='''hanning'''   ,num_mel_bins=self.num_mel_bins   ,dither=0.0   ,frame_shift=10   ,)

				__lowercase   =							fbank.shape[0]
				__lowercase   =							max_length - n_frames

				# pad or truncate, depending on difference
				if difference > 0:
							__lowercase   =							torch.nn.ZeroPadad((0, 0, 0, difference)       )
							__lowercase   =							pad_module(_lowerCamelCase       )
				elif difference < 0:
							__lowercase   =							fbank[0:max_length, :]

				__lowercase   =							fbank.numpy()

				return fbank


	def   _UpperCAmelCase   (self   ,_lowerCamelCase       )							->							np.ndarray:







				'''simple docstring'''





				return (input_values - (self.mean)) / (self.std * 2)


	def __call__(self   ,_lowerCamelCase   ,_lowerCamelCase = None   ,_lowerCamelCase = None   ,**_lowerCamelCase   ,)							->							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.'''       )

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

				if is_batched:
							__lowercase   =							[np.asarray(_lowerCamelCase   ,dtype=np.floataa       ) for speech in raw_speech]
				elif not is_batched and not isinstance(_lowerCamelCase   ,np.ndarray       ):
							__lowercase   =							np.asarray(_lowerCamelCase   ,dtype=np.floataa       )
				elif isinstance(_lowerCamelCase   ,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   =							[raw_speech]

				# extract fbank features and pad/truncate to max_length
				__lowercase   =							[self._extract_fbank_features(_lowerCamelCase   ,max_length=self.max_length       ) for waveform in raw_speech]

				# convert into BatchFeature
				__lowercase   =							BatchFeature({'''input_values''': features}       )

				# make sure list is in array format
				__lowercase   =							padded_inputs.get('''input_values'''       )
				if isinstance(input_values[0]   ,_lowerCamelCase       ):
							__lowercase   =							[np.asarray(_lowerCamelCase   ,dtype=np.floataa       ) for feature in input_values]

				# normalization
				if self.do_normalize:
							__lowercase   =							[self.normalize(_lowerCamelCase       ) for feature in input_values]

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

				return padded_inputs







'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest

from transformers import is_speech_available, is_torch_available
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_torch
from transformers.utils import FEATURE_EXTRACTOR_NAME


if is_speech_available() and is_torch_available():
						from transformers import SpeechTaFeatureExtractor, SpeechTaProcessor

						from .test_feature_extraction_speechta import floats_list


lowercase__		    =	get_tests_dir("fixtures/test_sentencepiece_bpe_char.model")






@require_torch
class      snake_case__    (	unittest.TestCase ):







		"""simple docstring"""

		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    List[str]			       =		tempfile.mkdtemp()

				snake_case   :    Optional[int]			       =		SpeechTaTokenizer(UpperCamelCase__	)
				tokenizer.save_pretrained(self.tmpdirname	)

				snake_case   :    Any			       =		{
				    '''feature_size''': 1,
				    '''padding_value''': 0.0,
				    '''sampling_rate''': 1_6000,
				    '''do_normalize''': False,
				    '''num_mel_bins''': 80,
				    '''hop_length''': 16,
				    '''win_length''': 64,
				    '''win_function''': '''hann_window''',
				    '''fmin''': 80,
				    '''fmax''': 7600,
				    '''mel_floor''': 1e-1_0,
				    '''reduction_factor''': 2,
				    '''return_attention_mask''': True,
				}

				snake_case   :    Tuple			       =		os.path.join(self.tmpdirname   ,     UpperCamelCase__	)
				with open(self.feature_extraction_file   ,     '''w'''   ,     encoding='''utf-8'''	) as fp:
						fp.write(json.dumps(UpperCamelCase__	) + '''\n'''	)



		def 	lowerCAmelCase							(	self							:       Dict   ,     **UpperCamelCase__							:       Any	)		->       str:






				"""simple docstring"""







				return SpeechTaTokenizer.from_pretrained(self.tmpdirname   ,     **UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Union[str, Any]   ,     **UpperCamelCase__							:       int	)		->       Optional[Any]:






				"""simple docstring"""







				return SpeechTaFeatureExtractor.from_pretrained(self.tmpdirname   ,     **UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Any	)		->       Any:






				"""simple docstring"""







				shutil.rmtree(self.tmpdirname	)



		def 	lowerCAmelCase							(	self							:       Tuple	)		->       Dict:






				"""simple docstring"""







				snake_case   :    str			       =		self.get_tokenizer()
				snake_case   :    List[str]			       =		self.get_feature_extractor()

				snake_case   :    Dict			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				processor.save_pretrained(self.tmpdirname	)
				snake_case   :    Dict			       =		SpeechTaProcessor.from_pretrained(self.tmpdirname	)

				self.assertEqual(processor.tokenizer.get_vocab()   ,     tokenizer.get_vocab()	)
				self.assertIsInstance(processor.tokenizer   ,     UpperCamelCase__	)

				self.assertEqual(processor.feature_extractor.to_json_string()   ,     feature_extractor.to_json_string()	)
				self.assertIsInstance(processor.feature_extractor   ,     UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       str	)		->       Any:






				"""simple docstring"""







				snake_case   :    int			       =		SpeechTaProcessor(tokenizer=self.get_tokenizer()   ,     feature_extractor=self.get_feature_extractor()	)
				processor.save_pretrained(self.tmpdirname	)

				snake_case   :    int			       =		self.get_tokenizer(bos_token='''(BOS)'''   ,     eos_token='''(EOS)'''	)
				snake_case   :    str			       =		self.get_feature_extractor(do_normalize=UpperCamelCase__   ,     padding_value=1.0	)

				snake_case   :    Tuple			       =		SpeechTaProcessor.from_pretrained(
				    self.tmpdirname   ,     bos_token='''(BOS)'''   ,     eos_token='''(EOS)'''   ,     do_normalize=UpperCamelCase__   ,     padding_value=1.0	)

				self.assertEqual(processor.tokenizer.get_vocab()   ,     tokenizer_add_kwargs.get_vocab()	)
				self.assertIsInstance(processor.tokenizer   ,     UpperCamelCase__	)

				self.assertEqual(processor.feature_extractor.to_json_string()   ,     feature_extractor_add_kwargs.to_json_string()	)
				self.assertIsInstance(processor.feature_extractor   ,     UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Dict:






				"""simple docstring"""







				snake_case   :    List[Any]			       =		self.get_feature_extractor()
				snake_case   :    List[str]			       =		self.get_tokenizer()

				snake_case   :    Union[str, Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Union[str, Any]			       =		floats_list((3, 1000)	)

				snake_case   :    List[str]			       =		feature_extractor(audio=UpperCamelCase__   ,     return_tensors='''np'''	)
				snake_case   :    Any			       =		processor(audio=UpperCamelCase__   ,     return_tensors='''np'''	)

				for key in input_feat_extract.keys():
						self.assertAlmostEqual(input_feat_extract[key].sum()   ,     input_processor[key].sum()   ,     delta=1e-2	)



		def 	lowerCAmelCase							(	self							:       Dict	)		->       str:






				"""simple docstring"""







				snake_case   :    str			       =		self.get_feature_extractor()
				snake_case   :    Optional[int]			       =		self.get_tokenizer()

				snake_case   :    Union[str, Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Dict			       =		floats_list((3, 1000)	)

				snake_case   :    str			       =		feature_extractor(audio_target=UpperCamelCase__   ,     return_tensors='''np'''	)
				snake_case   :    List[Any]			       =		processor(audio_target=UpperCamelCase__   ,     return_tensors='''np'''	)

				for key in input_feat_extract.keys():
						self.assertAlmostEqual(input_feat_extract[key].sum()   ,     input_processor[key].sum()   ,     delta=1e-2	)



		def 	lowerCAmelCase							(	self							:       List[Any]	)		->       int:






				"""simple docstring"""







				snake_case   :    Optional[int]			       =		self.get_feature_extractor()
				snake_case   :    Union[str, Any]			       =		self.get_tokenizer()

				snake_case   :    List[str]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Optional[Any]			       =		'''This is a test string'''

				snake_case   :    Dict			       =		processor(text=UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer(UpperCamelCase__	)

				for key in encoded_tok.keys():
						self.assertListEqual(encoded_tok[key]   ,     encoded_processor[key]	)



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Dict:






				"""simple docstring"""







				snake_case   :    Optional[int]			       =		self.get_feature_extractor()
				snake_case   :    str			       =		self.get_tokenizer()

				snake_case   :    str			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Dict			       =		'''This is a test string'''

				snake_case   :    Any			       =		processor(text_target=UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer(UpperCamelCase__	)

				for key in encoded_tok.keys():
						self.assertListEqual(encoded_tok[key]   ,     encoded_processor[key]	)



		def 	lowerCAmelCase							(	self							:       str	)		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    List[str]			       =		self.get_feature_extractor()
				snake_case   :    str			       =		self.get_tokenizer()

				snake_case   :    Optional[Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Optional[int]			       =		[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

				snake_case   :    List[str]			       =		processor.batch_decode(UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer.batch_decode(UpperCamelCase__	)

				self.assertListEqual(UpperCamelCase__   ,     UpperCamelCase__	)



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






				"""simple docstring"""







				snake_case   :    List[Any]			       =		self.get_feature_extractor()
				snake_case   :    Tuple			       =		self.get_tokenizer()

				snake_case   :    List[Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				self.assertListEqual(
				    processor.model_input_names   ,     feature_extractor.model_input_names   ,     msg='''`processor` and `feature_extractor` model input names do not match'''   ,     )


