






import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

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


lowerCamelCase      :       List[str]    =						logging.get_logger(__name__)



class 				_UpperCamelCase      (a_      ):
      snake_case_	=				["""input_values""", """attention_mask"""]


      def __init__(						self       ,    __UpperCamelCase = 1       ,    __UpperCamelCase = 1_6_0_0_0       ,    __UpperCamelCase = 0.0       ,    __UpperCamelCase = False       ,    __UpperCamelCase = 8_0       ,    __UpperCamelCase = 1_6       ,    __UpperCamelCase = 6_4       ,    __UpperCamelCase = "hann_window"       ,    __UpperCamelCase = 1.0       ,    __UpperCamelCase = 8_0       ,    __UpperCamelCase = 7_6_0_0       ,    __UpperCamelCase = 1e-10       ,    __UpperCamelCase = 2       ,    __UpperCamelCase = True       ,    **__UpperCamelCase       ,    )->						Optional[Any]:
           super().__init__(feature_size=__UpperCamelCase       ,    sampling_rate=__UpperCamelCase       ,    padding_value=__UpperCamelCase       ,    **__UpperCamelCase						)
           __lowerCAmelCase             =       do_normalize
           __lowerCAmelCase             =       return_attention_mask

           __lowerCAmelCase             =       num_mel_bins
           __lowerCAmelCase             =       hop_length
           __lowerCAmelCase             =       win_length
           __lowerCAmelCase             =       win_function
           __lowerCAmelCase             =       frame_signal_scale
           __lowerCAmelCase             =       fmin
           __lowerCAmelCase             =       fmax
           __lowerCAmelCase             =       mel_floor
           __lowerCAmelCase             =       reduction_factor

           __lowerCAmelCase             =       win_length * sampling_rate // 1_0_0_0
           __lowerCAmelCase             =       hop_length * sampling_rate // 1_0_0_0
           __lowerCAmelCase             =       optimal_fft_length(self.sample_size						)
           __lowerCAmelCase             =       (self.n_fft // 2) + 1

           __lowerCAmelCase             =       window_function(window_length=self.sample_size       ,    name=self.win_function       ,    periodic=__UpperCamelCase						)

           __lowerCAmelCase             =       mel_filter_bank(
               num_frequency_bins=self.n_freqs       ,    num_mel_filters=self.num_mel_bins       ,    min_frequency=self.fmin       ,    max_frequency=self.fmax       ,    sampling_rate=self.sampling_rate       ,    norm="slaney"       ,    mel_scale="slaney"       ,    )

           if frame_signal_scale != 1.0:
                warnings.warn(
                    "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"       ,    __UpperCamelCase       ,    )
           if reduction_factor != 2.0:
                warnings.warn(
                    "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"       ,    __UpperCamelCase       ,    )


      @staticmethod
      # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
      def 			__UpperCAmelCase		(						__UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase = 0.0						)->						List[np.ndarray]:
           if attention_mask is not None:
                __lowerCAmelCase             =       np.array(__UpperCamelCase       ,    np.intaa						)
                __lowerCAmelCase             =       []

                for vector, length in zip(__UpperCamelCase       ,    attention_mask.sum(-1						)						):
                     __lowerCAmelCase             =       (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7						)
                     if length < normed_slice.shape[0]:
                          __lowerCAmelCase             =       padding_value

                     normed_input_values.append(__UpperCamelCase						)
           else:
                __lowerCAmelCase             =       [(x - x.mean()) / np.sqrt(x.var() + 1e-7						) for x in input_values]

           return normed_input_values


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    )->						np.ndarray:
           __lowerCAmelCase             =       spectrogram(
               __UpperCamelCase       ,    window=self.window       ,    frame_length=self.sample_size       ,    hop_length=self.sample_stride       ,    fft_length=self.n_fft       ,    mel_filters=self.mel_filters       ,    mel_floor=self.mel_floor       ,    log_mel="log10"       ,    )
           return log_mel_spec.T


      def __call__(						self       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    __UpperCamelCase = False       ,    __UpperCamelCase = None       ,    __UpperCamelCase = False       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    **__UpperCamelCase       ,    )->						BatchFeature:
           if audio is None and audio_target is None:
                raise ValueError("You must provide either `audio` or `audio_target` values."						)

           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 audio is not None:
                __lowerCAmelCase             =       self._process_audio(
                    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    **__UpperCamelCase       ,    )
           else:
                __lowerCAmelCase             =       None

           if audio_target is not None:
                __lowerCAmelCase             =       self._process_audio(
                    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    **__UpperCamelCase       ,    )

                if inputs is None:
                     return inputs_target
                else:
                     __lowerCAmelCase             =       inputs_target["input_values"]
                     __lowerCAmelCase             =       inputs_target.get("attention_mask"						)
                     if decoder_attention_mask is not None:
                          __lowerCAmelCase             =       decoder_attention_mask

           return inputs


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase = False       ,    __UpperCamelCase = False       ,    __UpperCamelCase = None       ,    __UpperCamelCase = False       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    __UpperCamelCase = None       ,    **__UpperCamelCase       ,    )->						BatchFeature:
           __lowerCAmelCase             =       isinstance(__UpperCamelCase       ,    np.ndarray						) and len(speech.shape						) > 1
           if is_batched_numpy and len(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(speech[0]       ,    (np.ndarray, tuple, list)						))
           )

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

           # always return batch
           if not is_batched:
                __lowerCAmelCase             =       [speech]

           # needed to make pad() work on spectrogram inputs
           __lowerCAmelCase             =       self.feature_size

           # convert into correct format for padding
           if is_target:
                __lowerCAmelCase             =       [self._extract_mel_features(__UpperCamelCase						) for waveform in speech]
                __lowerCAmelCase             =       BatchFeature({"input_values": features}						)
                __lowerCAmelCase             =       self.num_mel_bins
           else:
                __lowerCAmelCase             =       BatchFeature({"input_values": speech}						)

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

           __lowerCAmelCase             =       feature_size_hack

           # convert input values to correct format
           __lowerCAmelCase             =       padded_inputs["input_values"]
           if not isinstance(input_values[0]       ,    np.ndarray						):
                __lowerCAmelCase             =       [np.asarray(__UpperCamelCase       ,    dtype=np.floataa						) for array in input_values]
           elif (
               not isinstance(__UpperCamelCase       ,    np.ndarray						)
               and isinstance(input_values[0]       ,    np.ndarray						)
               and input_values[0].dtype is np.dtype(np.floataa						)
           ):
                __lowerCAmelCase             =       [array.astype(np.floataa						) for array in input_values]
           elif isinstance(__UpperCamelCase       ,    np.ndarray						) and input_values.dtype is np.dtype(np.floataa						):
                __lowerCAmelCase             =       input_values.astype(np.floataa						)

           # convert attention_mask to correct format
           __lowerCAmelCase             =       padded_inputs.get("attention_mask"						)
           if attention_mask is not None:
                __lowerCAmelCase             =       [np.asarray(__UpperCamelCase       ,    dtype=np.intaa						) for array in attention_mask]

           # zero-mean and unit-variance normalization
           if not is_target and self.do_normalize:
                __lowerCAmelCase             =       (
                    attention_mask
                    if self._get_padding_strategies(__UpperCamelCase       ,    max_length=__UpperCamelCase						) is not PaddingStrategy.DO_NOT_PAD
                    else None
                )
                __lowerCAmelCase             =       self.zero_mean_unit_var_norm(
                    padded_inputs["input_values"]       ,    attention_mask=__UpperCamelCase       ,    padding_value=self.padding_value						)

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

           return padded_inputs


      def 			__UpperCAmelCase		(						self						)->						Dict[str, Any]:
           __lowerCAmelCase             =       super().to_dict()

           # Don't serialize these as they are derived from the other properties.
           __lowerCAmelCase             =       ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
           for name in names:
                if name in output:
                     del output[name]

           return output














from sklearn.metrics import fa_score

import datasets


lowerCamelCase      :       Union[str, Any]    =						'''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


lowerCamelCase      :       Optional[Any]    =						'''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


lowerCamelCase      :       Optional[Any]    =						'''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''



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


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           return datasets.MetricInfo(
               description=_DESCRIPTION       ,    citation=_CITATION       ,    inputs_description=_KWARGS_DESCRIPTION       ,    features=datasets.Features(
                   {
                       "predictions": datasets.Sequence(datasets.Value("int32"						)						),
                       "references": datasets.Sequence(datasets.Value("int32"						)						),
                   }
                   if self.config_name == "multilabel"
                   else {
                       "predictions": datasets.Value("int32"						),
                       "references": datasets.Value("int32"						),
                   }						)       ,    reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"]       ,    )


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase=None       ,    __UpperCamelCase=1       ,    __UpperCamelCase="binary"       ,    __UpperCamelCase=None						)->						Optional[int]:
           __lowerCAmelCase             =       fa_score(
               __UpperCamelCase       ,    __UpperCamelCase       ,    labels=__UpperCamelCase       ,    pos_label=__UpperCamelCase       ,    average=__UpperCamelCase       ,    sample_weight=__UpperCamelCase						)
           return {"f1": float(__UpperCamelCase						) if score.size == 1 else score}






