




from typing import List, Optional, Union

import numpy as np

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


__A        =    logging.get_logger(__name__)







class     __lowerCAmelCase (       __magic_name__ ):

			"""simple docstring"""







			snake_case_   		=       ['''input_values''', '''padding_mask''']


			def __init__(      self			,						lowerCamelCase__ = 1			,						lowerCamelCase__ = 24_000			,						lowerCamelCase__ = 0.0			,						lowerCamelCase__ = None			,						lowerCamelCase__ = None			,						**lowerCamelCase__			,						)    ->      Union[str, Any]:



							'''simple docstring'''
							super().__init__(feature_size=lowerCamelCase__			,						sampling_rate=lowerCamelCase__			,						padding_value=lowerCamelCase__			,						**lowerCamelCase__							)
							__lowerCamelCase		       =    chunk_length_s
							__lowerCamelCase		       =    overlap


			@property
			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							if self.chunk_length_s is None:
											return None
							else:
											return int(self.chunk_length_s * self.sampling_rate							)


			@property
			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							if self.chunk_length_s is None or self.overlap is None:
											return None
							else:
											return max(1			,						int((1.0 - self.overlap) * self.chunk_length							)							)






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__ = None			,						lowerCamelCase__ = False			,						lowerCamelCase__ = None			,						lowerCamelCase__ = None			,						lowerCamelCase__ = None			,						)    ->      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 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 padding and truncation:
											raise ValueError('Both padding and truncation were set. Make sure you only set one.'							)
							elif padding is None:
											# by default let's pad the inputs
											__lowerCamelCase		       =    True

							__lowerCamelCase		       =    bool(
							    isinstance(lowerCamelCase__			,						(list, tuple)							) and (isinstance(raw_audio[0]			,						(np.ndarray, tuple, list)							))							)

							if is_batched:
											__lowerCamelCase		       =    [np.asarray(lowerCamelCase__			,						dtype=np.floataa							).T for audio in raw_audio]
							elif not is_batched and not isinstance(lowerCamelCase__			,						np.ndarray							):
											__lowerCamelCase		       =    np.asarray(lowerCamelCase__			,						dtype=np.floataa							)
							elif isinstance(lowerCamelCase__			,						np.ndarray							) and raw_audio.dtype is np.dtype(np.floataa							):
											__lowerCamelCase		       =    raw_audio.astype(np.floataa							)

							# always return batch
							if not is_batched:
											__lowerCamelCase		       =    [np.asarray(lowerCamelCase__							).T]

							# verify inputs are valid
							for idx, example in enumerate(lowerCamelCase__							):
											if example.ndim > 2:
															raise ValueError(f"""Expected input shape (channels, length) but got shape {example.shape}"""							)
											if self.feature_size == 1 and example.ndim != 1:
															raise ValueError(f"""Expected mono audio but example has {example.shape[-1]} channels"""							)
											if self.feature_size == 2 and example.shape[-1] != 2:
															raise ValueError(f"""Expected stereo audio but example has {example.shape[-1]} channels"""							)

							__lowerCamelCase		       =    None
							__lowerCamelCase		       =    BatchFeature({'input_values': raw_audio}							)
							if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
											if truncation:
															__lowerCamelCase		       =    min(array.shape[0] for array in raw_audio							)
															__lowerCamelCase		       =    int(np.floor(max_length / self.chunk_stride							)							)
															__lowerCamelCase		       =    (nb_step - 1) * self.chunk_stride + self.chunk_length
											elif padding:
															__lowerCamelCase		       =    max(array.shape[0] for array in raw_audio							)
															__lowerCamelCase		       =    int(np.ceil(max_length / self.chunk_stride							)							)
															__lowerCamelCase		       =    (nb_step - 1) * self.chunk_stride + self.chunk_length
															__lowerCamelCase		       =    'max_length'
											else:
															__lowerCamelCase		       =    input_values

        # normal padding on batch
							if padded_inputs is None:
											__lowerCamelCase		       =    self.pad(
											    lowerCamelCase__			,						max_length=lowerCamelCase__			,						truncation=lowerCamelCase__			,						padding=lowerCamelCase__			,						return_attention_mask=lowerCamelCase__			,						)
											if padding:
															__lowerCamelCase		       =    padded_inputs.pop('attention_mask'							)

							__lowerCamelCase		       =    []
							for example in padded_inputs.pop('input_values'							):
											if self.feature_size == 1:
															__lowerCamelCase		       =    example[..., None]
											input_values.append(example.T							)

							__lowerCamelCase		       =    input_values
							if return_tensors is not None:
											__lowerCamelCase		       =    padded_inputs.convert_to_tensors(lowerCamelCase__							)

							return padded_inputs







'''simple docstring'''






import warnings
from contextlib import contextmanager

from ....processing_utils import ProcessorMixin

class 				SCREAMING_SNAKE_CASE(							A__			):







	"""simple docstring"""






	lowerCamelCase__			 =       """MCTCTFeatureExtractor"""
	lowerCamelCase__			 =       """AutoTokenizer"""







	def __init__(						self			:     Dict		,			__snake_case			:     Optional[int]		,			__snake_case			:     List[str]		)			->		str:
								super().__init__(__snake_case		,			__snake_case		)
								UpperCAmelCase :       List[Any] 							=		self.feature_extractor
								UpperCAmelCase :       Union[str, Any] 							=		False







	def __call__(						self			:     Any		,			*__snake_case			:     List[str]		,			**__snake_case			:     Any		)			->		List[Any]:
								# For backward compatibility
								if self._in_target_context_manager:
															return self.current_processor(*__snake_case		,			**__snake_case		)

								if "raw_speech" in kwargs:
															warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'''		)
															UpperCAmelCase :       int 							=		kwargs.pop('''raw_speech'''		)
								else:
															UpperCAmelCase :       Union[str, Any] 							=		kwargs.pop('''audio'''		,			__snake_case		)
								UpperCAmelCase :       Optional[Any] 							=		kwargs.pop('''sampling_rate'''		,			__snake_case		)
								UpperCAmelCase :       Dict 							=		kwargs.pop('''text'''		,			__snake_case		)
								if len(__snake_case		) > 0:
															UpperCAmelCase :       Any 							=		args[0]
															UpperCAmelCase :       Optional[int] 							=		args[1:]

								if audio is None and text is None:
															raise ValueError('''You need to specify either an `audio` or `text` input to process.'''		)

								if audio is not None:
															UpperCAmelCase :       List[str] 							=		self.feature_extractor(__snake_case		,			*__snake_case		,			sampling_rate=__snake_case		,			**__snake_case		)
								if text is not None:
															UpperCAmelCase :       int 							=		self.tokenizer(__snake_case		,			**__snake_case		)

								if text is None:
															return inputs
								elif audio is None:
															return encodings
								else:
															UpperCAmelCase :       str 							=		encodings['''input_ids''']
															return inputs







	def      A	(						self			:     List[Any]		,			*__snake_case			:     List[Any]		,			**__snake_case			:     List[Any]		)			->		str:
								return self.tokenizer.batch_decode(*__snake_case		,			**__snake_case		)







	def      A	(						self			:     List[Any]		,			*__snake_case			:     int		,			**__snake_case			:     Optional[int]		)			->		Any:
								# For backward compatibility
								if self._in_target_context_manager:
															return self.current_processor.pad(*__snake_case		,			**__snake_case		)

								UpperCAmelCase :       List[Any] 							=		kwargs.pop('''input_features'''		,			__snake_case		)
								UpperCAmelCase :       Optional[Any] 							=		kwargs.pop('''labels'''		,			__snake_case		)
								if len(__snake_case		) > 0:
															UpperCAmelCase :       List[str] 							=		args[0]
															UpperCAmelCase :       List[Any] 							=		args[1:]

								if input_features is not None:
															UpperCAmelCase :       Tuple 							=		self.feature_extractor.pad(__snake_case		,			*__snake_case		,			**__snake_case		)
								if labels is not None:
															UpperCAmelCase :       Optional[int] 							=		self.tokenizer.pad(__snake_case		,			**__snake_case		)

								if labels is None:
															return input_features
								elif input_features is None:
															return labels
								else:
															UpperCAmelCase :       List[str] 							=		labels['''input_ids''']
															return input_features







	def      A	(						self			:     Union[str, Any]		,			*__snake_case			:     Optional[Any]		,			**__snake_case			:     Optional[int]		)			->		Optional[Any]:
								return self.tokenizer.decode(*__snake_case		,			**__snake_case		)







	@contextmanager
	def      A	(						self			:     Any		)			->		Optional[int]:
								warnings.warn(
								    '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
								    '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
								    '''your audio inputs, or in a separate call.'''		)
								UpperCAmelCase :       Dict 							=		True
								UpperCAmelCase :       List[Any] 							=		self.tokenizer
								yield
								UpperCAmelCase :       Tuple 							=		self.feature_extractor
								UpperCAmelCase :       List[Any] 							=		False





