

from math import ceil
from typing import List, Optional, Union

import numpy as np

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


lowerCAmelCase__								=		logging.get_logger(__name__)







class 	lowercase    (				UpperCamelCase_							):


		"""simple docstring"""




		a__					       =  ["audio_values", "audio_mask"]


		def __init__(				self	,       __snake_case=20_48	,       __snake_case=1	,       __snake_case=[16, 16]	,       __snake_case=1_28	,       __snake_case=4_41_00	,       __snake_case=86	,       __snake_case=20_48	,       __snake_case=0.0	,       **__snake_case	,       ):
			super().__init__(
			    feature_size=__snake_case	,       sampling_rate=__snake_case	,       padding_value=__snake_case	,       **__snake_case	,       )

			_UpperCamelCase   :		Optional[int]			=  spectrogram_length
			_UpperCamelCase   :		Optional[int]			=  num_channels
			_UpperCamelCase   :		Any			=  patch_size
			_UpperCamelCase   :		Any			=  feature_size // self.patch_size[1]
			_UpperCamelCase   :		List[str]			=  n_fft
			_UpperCamelCase   :		Optional[Any]			=  sampling_rate // hop_length_to_sampling_rate
			_UpperCamelCase   :		List[str]			=  sampling_rate
			_UpperCamelCase   :		Any			=  padding_value
			_UpperCamelCase   :		Dict			=  mel_filter_bank(
			    num_frequency_bins=1 + n_fft // 2	,       num_mel_filters=__snake_case	,       min_frequency=0.0	,       max_frequency=2_2_0_5_0.0	,       sampling_rate=__snake_case	,       norm='slaney'	,       mel_scale='slaney'	,       ).T


		def 		A__					(				self	,       __snake_case):
			_UpperCamelCase   :		str			=  spectrogram(
			    __snake_case	,       window_function(self.n_fft	,       'hann')	,       frame_length=self.n_fft	,       hop_length=self.hop_length	,       power=2.0	,       mel_filters=self.mel_filters.T	,       log_mel='dB'	,       db_range=8_0.0	,       )
			_UpperCamelCase   :		Optional[Any]			=  log_spec[:, :-1]
			_UpperCamelCase   :		Any			=  log_spec - 2_0.0
			_UpperCamelCase   :		Any			=  np.clip(log_spec / 4_0.0	,       -2.0	,       0.0) + 1.0
			return log_spec






		def __call__(				self	,       __snake_case	,       __snake_case = None	,       __snake_case = True	,       __snake_case = None	,       __snake_case = False	,       __snake_case = False	,       **__snake_case	,       ):

			if sampling_rate is not None:
				if sampling_rate != self.sampling_rate:
					raise ValueError(
					    'This feature extractor is set to support sampling rate'
					    f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'''
					    f''' 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.')

			_UpperCamelCase   :		int			=  isinstance(__snake_case	,       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   :		Optional[int]			=  is_batched_numpy or (
			    isinstance(__snake_case	,       (list, tuple)) and (isinstance(raw_speech[0]	,       (np.ndarray, tuple, list)))
			)
			if is_batched:
				_UpperCamelCase   :		List[str]			=  [np.asarray([speech]	,       dtype=np.floataa).T for speech in raw_speech]
			elif not is_batched and not isinstance(__snake_case	,       np.ndarray):
				_UpperCamelCase   :		List[Any]			=  np.asarray(__snake_case	,       dtype=np.floataa)
			elif isinstance(__snake_case	,       np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
				_UpperCamelCase   :		str			=  raw_speech.astype(np.floataa)
			# always return batch
			if not is_batched:
				_UpperCamelCase   :		List[Any]			=  [np.asarray([raw_speech]).T]

			# Convert audio signals to log mel spectrograms, truncate by time axis
			_UpperCamelCase   :		Optional[int]			=  [
			    self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
			]
			if isinstance(audio_features[0]	,       __snake_case):
				_UpperCamelCase   :		Optional[Any]			=  [np.asarray(__snake_case	,       dtype=np.floataa) for feature in audio_features]

			# Create audio attention mask
			_UpperCamelCase   :		Optional[int]			=  max(
			    [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features])  # The maximum number of audio patches in a batch
			if return_attention_mask:
				_UpperCamelCase   :		Union[str, Any]			=  [
				    (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
				    + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
				    for feature in audio_features
				]
				_UpperCamelCase   :		List[Any]			=  np.array(__snake_case).astype(np.floataa)

			# convert into correct format for padding
			_UpperCamelCase   :		Optional[Any]			=  max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
			_UpperCamelCase   :		int			=  np.ones([len(__snake_case), 1, max_time_len, self.feature_size]).astype(np.floataa)
			_UpperCamelCase   :		List[str]			=  padded_audio_features * self.padding_value
			for i in range(len(__snake_case)):
				_UpperCamelCase   :		str			=  audio_features[i]
				_UpperCamelCase   :		str			=  feature

			# return as BatchFeature
			if return_attention_mask:
				_UpperCamelCase   :		List[Any]			=  {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask}
			else:
				_UpperCamelCase   :		Union[str, Any]			=  {'''audio_values''': padded_audio_features}

			_UpperCamelCase   :		Dict			=  BatchFeature(data=__snake_case	,       tensor_type=__snake_case)
			return encoded_inputs







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool







class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		a__					       =  "facebook/bart-large-mnli"
		a__					       =  (
		    "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which "
		    "should be the text to classify, and `labels`, which should be the list of labels to use for classification. "
		    "It returns the most likely label in the list of provided `labels` for the input text."
		)
		a__					       =  "text_classifier"
		a__					       =  AutoTokenizer
		a__					       =  AutoModelForSequenceClassification

		a__					       =  ["text", ["text"]]
		a__					       =  ["text"]


		def 		A__					(				self):
			super().setup()
			_UpperCamelCase   :		List[Any]			=						self.model.config
			_UpperCamelCase   :		Optional[int]			=						-1
			for idx, label in config.idalabel.items():
				if label.lower().startswith('entail'):
					_UpperCamelCase   :		Tuple			=						int(__snake_case)
			if self.entailment_id == -1:
				raise ValueError('Could not determine the entailment ID from the model config, please pass it at init.')


		def 		A__					(				self	,       __snake_case	,       __snake_case):
			_UpperCamelCase   :		List[Any]			=						labels
			return self.pre_processor(
			    [text] * len(__snake_case)	,       [f'''This example is {label}''' for label in labels]	,       return_tensors='pt'	,       padding='max_length'	,       )






		def 		A__					(				self	,       __snake_case):
			_UpperCamelCase   :		str			=						outputs.logits
			_UpperCamelCase   :		Optional[Any]			=						torch.argmax(logits[:, 2]).item()
			return self._labels[label_id]




