
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 PaddingStrategy, TensorType, logging


A		: int								=     logging.get_logger(__name__)



class    a_ (			_a    ):
			a	:			List[Any]					   =							['''input_features''', '''attention_mask''']






			def __init__(      self				,			__UpperCamelCase=80				,			__UpperCamelCase=16_000				,			__UpperCamelCase=80				,			__UpperCamelCase=0.0				,			__UpperCamelCase=True				,			__UpperCamelCase=True				,			__UpperCamelCase=True				,			**__UpperCamelCase				,			):
									super().__init__(feature_size=__UpperCamelCase				,			sampling_rate=__UpperCamelCase				,			padding_value=__UpperCamelCase				,			**__UpperCamelCase  )
									_lowercase					       =					num_mel_bins
									_lowercase					       =					do_ceptral_normalize
									_lowercase					       =					normalize_means
									_lowercase					       =					normalize_vars
									_lowercase					       =					True






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			):
									_lowercase					       =					waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
									_lowercase					       =					torch.from_numpy(__UpperCamelCase  ).unsqueeze(0  )
									_lowercase					       =					ta_kaldi.fbank(__UpperCamelCase				,			num_mel_bins=self.num_mel_bins				,			sample_frequency=self.sampling_rate  )
									return features.numpy()






			@staticmethod
			def    UpperCamelCase_				(      __UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase = True				,			__UpperCamelCase = True				,			__UpperCamelCase = 0.0				,			):
									# make sure we normalize float32 arrays
									if normalize_means:
															_lowercase					       =					x[:input_length].mean(axis=0  )
															_lowercase					       =					np.subtract(__UpperCamelCase				,			__UpperCamelCase  )
									if normalize_vars:
															_lowercase					       =					x[:input_length].std(axis=0  )
															_lowercase					       =					np.divide(__UpperCamelCase				,			__UpperCamelCase  )

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

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

									return x






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase = None  ):
									_lowercase					       =					attention_mask.sum(-1  ) if attention_mask is not None else [x.shape[0] for x in input_features]
									return [
									    self.utterance_cmvn(__UpperCamelCase				,			__UpperCamelCase				,			self.normalize_means				,			self.normalize_vars				,			self.padding_value  )
									    for x, n in zip(__UpperCamelCase				,			__UpperCamelCase  )
									]






			def __call__(      self				,			__UpperCamelCase				,			__UpperCamelCase = False				,			__UpperCamelCase = None				,			__UpperCamelCase = False				,			__UpperCamelCase = None				,			__UpperCamelCase = None				,			__UpperCamelCase = None				,			__UpperCamelCase = None				,			**__UpperCamelCase				,			):

									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(__UpperCamelCase				,			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(__UpperCamelCase				,			(list, tuple)  ) and (isinstance(raw_speech[0]				,			(np.ndarray, tuple, list)  ))
									)

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

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

									_lowercase					       =					self.pad(
									    __UpperCamelCase				,			padding=__UpperCamelCase				,			max_length=__UpperCamelCase				,			truncation=__UpperCamelCase				,			pad_to_multiple_of=__UpperCamelCase				,			return_attention_mask=__UpperCamelCase				,			**__UpperCamelCase				,			)

									# make sure list is in array format
									_lowercase					       =					padded_inputs.get("""input_features"""  )
									if isinstance(input_features[0]				,			__UpperCamelCase  ):
															_lowercase					       =					[np.asarray(__UpperCamelCase				,			dtype=np.floataa  ) for feature in input_features]

									_lowercase					       =					padded_inputs.get("""attention_mask"""  )
									if attention_mask is not None:
															_lowercase					       =					[np.asarray(__UpperCamelCase				,			dtype=np.intaa  ) for array in attention_mask]

									# Utterance-level cepstral mean and variance normalization
									if self.do_ceptral_normalize:
															_lowercase					       =					(
															    np.array(__UpperCamelCase				,			dtype=np.intaa  )
															    if self._get_padding_strategies(__UpperCamelCase				,			max_length=__UpperCamelCase  ) is not PaddingStrategy.DO_NOT_PAD
															    else None
															)
															_lowercase					       =					self.normalize(
															    padded_inputs["""input_features"""]				,			attention_mask=__UpperCamelCase  )

									if return_tensors is not None:
															_lowercase					       =					padded_inputs.convert_to_tensors(__UpperCamelCase  )

									return padded_inputs

import datasets


A		: Optional[int]								=     '''\
@InProceedings{conneau2018xnli,
  author = "Conneau, Alexis
                 and Rinott, Ruty
                 and Lample, Guillaume
                 and Williams, Adina
                 and Bowman, Samuel R.
                 and Schwenk, Holger
                 and Stoyanov, Veselin",
  title = "XNLI: Evaluating Cross-lingual Sentence Representations",
  booktitle = "Proceedings of the 2018 Conference on Empirical Methods
               in Natural Language Processing",
  year = "2018",
  publisher = "Association for Computational Linguistics",
  location = "Brussels, Belgium",
}
'''

A		: Optional[int]								=     '''\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
'''

A		: str								=     '''
Computes XNLI score which is just simple accuracy.
Args:
    predictions: Predicted labels.
    references: Ground truth labels.
Returns:
    \'accuracy\': accuracy
Examples:

    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> xnli_metric = datasets.load_metric("xnli")
    >>> results = xnli_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0}
'''




def 	UpperCamelCase__  (     SCREAMING_SNAKE_CASE_	:	List[str]		,   SCREAMING_SNAKE_CASE_	:	List[Any]       )  ->     str:
						return (preds == labels).mean()



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,			_KWARGS_DESCRIPTION    )
class    a_ (			datasets.Metric    ):






			def    UpperCamelCase_				(      self  ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION				,			citation=_CITATION				,			inputs_description=_KWARGS_DESCRIPTION				,			features=datasets.Features(
									        {
									            """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32"""  ),
									            """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32"""  ),
									        }  )				,			codebase_urls=[]				,			reference_urls=[]				,			format="""numpy"""				,			)






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase  ):
									return {"accuracy": simple_accuracy(__UpperCamelCase				,			__UpperCamelCase  )}