


from typing import List, Optional

import numpy as np

from ...processing_utils import ProcessorMixin
from ...utils import to_numpy


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       a  :    Tuple       ="EncodecFeatureExtractor"
       a  :    List[Any]       =("T5Tokenizer", "T5TokenizerFast")

       def __init__(						self		,					snake_case__		,					snake_case__						):






         """simple docstring"""





         super().__init__(snake_case__		,					snake_case__						)
         lowerCAmelCase					:					int								=							self.feature_extractor
         lowerCAmelCase					:					int								=							False

       def 	lowercase__							(						self		,					snake_case__=None		,					snake_case__=None		,					snake_case__=True						):






         """simple docstring"""





         return self.tokenizer.get_decoder_prompt_ids(task=snake_case__		,					language=snake_case__		,					no_timestamps=snake_case__						)

       def __call__(						self		,					*snake_case__		,					**snake_case__						):






         """simple docstring"""





         if self._in_target_context_manager:
           return self.current_processor(*snake_case__		,					**snake_case__						)

         lowerCAmelCase					:					int								=							kwargs.pop("audio"		,					snake_case__						)
         lowerCAmelCase					:					Optional[Any]								=							kwargs.pop("sampling_rate"		,					snake_case__						)
         lowerCAmelCase					:					List[Any]								=							kwargs.pop("text"		,					snake_case__						)
         if len(snake_case__						) > 0:
           lowerCAmelCase					:					List[str]								=							args[0]
           lowerCAmelCase					:					Tuple								=							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 text is not None:
           lowerCAmelCase					:					Union[str, Any]								=							self.tokenizer(snake_case__		,					**snake_case__						)

         if audio is not None:
           lowerCAmelCase					:					int								=							self.feature_extractor(snake_case__		,					*snake_case__		,					sampling_rate=snake_case__		,					**snake_case__						)

         if audio is None:
           return inputs

         elif text is None:
           return audio_inputs

         else:
           lowerCAmelCase					:					List[str]								=							audio_inputs["input_values"]
           if "padding_mask" in audio_inputs:
             lowerCAmelCase					:					Tuple								=							audio_inputs["padding_mask"]
           return inputs

       def 	lowercase__							(						self		,					*snake_case__		,					**snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					int								=							kwargs.pop("audio"		,					snake_case__						)
         lowerCAmelCase					:					Dict								=							kwargs.pop("padding_mask"		,					snake_case__						)

         if len(snake_case__						) > 0:
           lowerCAmelCase					:					Optional[int]								=							args[0]
           lowerCAmelCase					:					Optional[int]								=							args[1:]

         if audio_values is not None:
           return self._decode_audio(snake_case__		,					padding_mask=snake_case__						)
         else:
           return self.tokenizer.batch_decode(*snake_case__		,					**snake_case__						)

       def 	lowercase__							(						self		,					*snake_case__		,					**snake_case__						):






         """simple docstring"""





         return self.tokenizer.decode(*snake_case__		,					**snake_case__						)







       def 	lowercase__							(						self		,					snake_case__		,					snake_case__ = None						):






         """simple docstring"""





         lowerCAmelCase					:					Optional[Any]								=							to_numpy(snake_case__						)
         lowerCAmelCase					:					Optional[int]								=							audio_values.shape

         if padding_mask is None:
           return list(snake_case__						)

         lowerCAmelCase					:					List[Any]								=							to_numpy(snake_case__						)

         # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
         # token (so that the generated audio values are **not** treated as padded tokens)
         lowerCAmelCase					:					Any								=							seq_len - padding_mask.shape[-1]
         lowerCAmelCase					:					int								=							1 - self.feature_extractor.padding_value
         lowerCAmelCase					:					Optional[int]								=							np.pad(snake_case__		,					((0, 0), (0, difference))		,					"constant"		,					constant_values=snake_case__						)

         lowerCAmelCase					:					Any								=							audio_values.tolist()
         for i in range(snake_case__						):
           lowerCAmelCase					:					List[Any]								=							np.asarray(audio_values[i]						)[
               padding_mask[i][None, :] != self.feature_extractor.padding_value
           ]
           lowerCAmelCase					:					int								=							sliced_audio.reshape(snake_case__		,					-1						)

         return audio_values









"""simple docstring"""







from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
     import importlib_metadata
else:
     import importlib.metadata as importlib_metadata


lowerCAmelCase__				    =       ''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):


     class 				SCREAMING_SNAKE_CASE__    (		tr.AbstractTransform    ):
            """simple docstring"""


            def __init__(						self		,					snake_case__ = " "						):






              """simple docstring"""





              lowerCAmelCase					:					List[Any]								=							sentence_delimiter

            def 	lowercase__							(						self		,					snake_case__						):






              """simple docstring"""





              return list(snake_case__						)







            def 	lowercase__							(						self		,					snake_case__						):






              """simple docstring"""





              lowerCAmelCase					:					Any								=							[]
              for sent_idx, sentence in enumerate(snake_case__						):
                chars.extend(self.process_string(snake_case__						)						)
                if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(snake_case__						) - 1:
                  chars.append(self.sentence_delimiter						)
              return chars

     lowerCAmelCase__				    =       tr.Compose(
         [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
     )
else:
     lowerCAmelCase__				    =       tr.Compose(
         [
             tr.RemoveMultipleSpaces(),
             tr.Strip(),
             tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
             tr.ReduceToListOfListOfChars(),
         ]
     )


lowerCAmelCase__				    =       '''\
@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.}
}
'''

lowerCAmelCase__				    =       '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (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 characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

lowerCAmelCase__				    =       '''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,   _KWARGS_DESCRIPTION    )
class 				SCREAMING_SNAKE_CASE__    (		datasets.Metric    ):
       """simple docstring"""


       def 	lowercase__							(						self						):






         """simple docstring"""





         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",
                 "https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
             ]		,					)







       def 	lowercase__							(						self		,					snake_case__		,					snake_case__		,					snake_case__=False						):






         """simple docstring"""





         if concatenate_texts:
           return jiwer.compute_measures(
               snake_case__		,					snake_case__		,					truth_transform=snake_case__		,					hypothesis_transform=snake_case__		,					)["wer"]

         lowerCAmelCase					:					List[Any]								=							0
         lowerCAmelCase					:					Optional[Any]								=							0
         for prediction, reference in zip(snake_case__		,					snake_case__						):
           lowerCAmelCase					:					Optional[int]								=							jiwer.compute_measures(
               snake_case__		,					snake_case__		,					truth_transform=snake_case__		,					hypothesis_transform=snake_case__		,					)
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

         return incorrect / total





