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


A_    							=					logging.get_logger(__name__)




class  __lowerCamelCase  ( lowerCAmelCase			):
				a__:      Union[str, Any]          =    ['input_features', 'attention_mask']




				def __init__(				self							,						UpperCAmelCase=80							,						UpperCAmelCase=1_6000							,						UpperCAmelCase=80							,						UpperCAmelCase=0.0							,						UpperCAmelCase=True							,						UpperCAmelCase=True							,						UpperCAmelCase=True							,						**UpperCAmelCase							,						):
							super().__init__(feature_size=UpperCAmelCase							,						sampling_rate=UpperCAmelCase							,						padding_value=UpperCAmelCase							,						**UpperCAmelCase   )
							lowerCamelCase_					=  num_mel_bins
							lowerCamelCase_					=  do_ceptral_normalize
							lowerCamelCase_					=  normalize_means
							lowerCamelCase_					=  normalize_vars
							lowerCamelCase_					=  True




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						):
							lowerCamelCase_					=  waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
							lowerCamelCase_					=  torch.from_numpy(UpperCAmelCase   ).unsqueeze(0   )
							lowerCamelCase_					=  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:
										lowerCamelCase_					=  x[:input_length].mean(axis=0   )
										lowerCamelCase_					=  np.subtract(UpperCAmelCase							,						UpperCAmelCase   )
							if normalize_vars:
										lowerCamelCase_					=  x[:input_length].std(axis=0   )
										lowerCamelCase_					=  np.divide(UpperCAmelCase							,						UpperCAmelCase   )

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

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

							return x




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase = None   ):
							lowerCamelCase_					=  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.'''   )

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

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

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

							# extract fbank features
							lowerCamelCase_					=  [self._extract_fbank_features(UpperCAmelCase   ) for waveform in raw_speech]

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

							lowerCamelCase_					=  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
							lowerCamelCase_					=  padded_inputs.get('''input_features'''   )
							if isinstance(input_features[0]							,						UpperCAmelCase   ):
										lowerCamelCase_					=  [np.asarray(UpperCAmelCase							,						dtype=np.floataa   ) for feature in input_features]

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

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

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

							return padded_inputs





"""simple docstring"""


from jiwer import compute_measures

import datasets


A_    							=					"""\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""

A_    							=					"""\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.

This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.

Word error rate can then be computed as:

WER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
"""

A_    							=					"""
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> wer = datasets.load_metric(\"wer\")
    >>> wer_score = wer.compute(predictions=predictions, references=references)
    >>> print(wer_score)
    0.5
"""




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




				def        UpperCAmelCase__						(				self   ):
							return datasets.MetricInfo(
							    description=_DESCRIPTION							,						citation=_CITATION							,						inputs_description=_KWARGS_DESCRIPTION							,						features=datasets.Features(
							        {
							            '''predictions''': datasets.Value('''string'''							,						id='''sequence'''   ),
							            '''references''': datasets.Value('''string'''							,						id='''sequence'''   ),
							        }   )							,						codebase_urls=['''https://github.com/jitsi/jiwer/''']							,						reference_urls=[
							        '''https://en.wikipedia.org/wiki/Word_error_rate''',
							    ]							,						)





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase=None							,						UpperCAmelCase=None							,						UpperCAmelCase=False   ):
							if concatenate_texts:
										return compute_measures(UpperCAmelCase							,						UpperCAmelCase   )["wer"]
							else:
										lowerCamelCase_					=  0
										lowerCamelCase_					=  0
										for prediction, reference in zip(UpperCAmelCase							,						UpperCAmelCase   ):
													lowerCamelCase_					=  compute_measures(UpperCAmelCase							,						UpperCAmelCase   )
													incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
													total += measures["substitutions"] + measures["deletions"] + measures["hits"]
										return incorrect / total



