





"""simple docstring"""




from jiwer import compute_measures

import datasets


__lowerCamelCase	:					str			  =					"""\
@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	:					Optional[Any]			  =					"""\
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.
"""

__lowerCamelCase	:					List[Any]			  =					"""
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  A__       (	datasets.Metric      ):





      def 	__UpperCamelCase(			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",
           ]	,							)





      def 	__UpperCamelCase(			self	,							A_=None	,							A_=None	,							A_=False       ):
       '''simple docstring'''




       if concatenate_texts:
        return compute_measures(A_	,							A_       )["wer"]
       else:
        UpperCamelCase     : Any	     =       0
        UpperCamelCase     : Optional[Any]	     =       0
        for prediction, reference in zip(A_	,							A_       ):
         UpperCamelCase     : Dict	     =       compute_measures(A_	,							A_       )
         incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
         total += measures["substitutions"] + measures["deletions"] + measures["hits"]
        return incorrect / total







import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


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


__lowerCamelCase	:					Any			  =					r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       raise NotImplementedError("StoppingCriteria needs to be subclassed"       )



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       max_length
       UpperCamelCase     : Dict	     =       max_position_embeddings





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       input_ids.shape[-1]
       UpperCamelCase     : str	     =       cur_len >= self.max_length
       if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
        logger.warning_once(
            "This is a friendly reminder - the current text generation call will exceed the model's predefined "
            F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
            "exceptions, performance degradation, or nothing at all."       )
       return is_done



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_       ):
       '''simple docstring'''




       warnings.warn(
           "The class `MaxNewTokensCriteria` is deprecated. "
           F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
           "with `max_length = start_length + max_new_tokens` instead."	,							A_	,							)
       UpperCamelCase     : Union[str, Any]	     =       start_length
       UpperCamelCase     : List[str]	     =       max_new_tokens
       UpperCamelCase     : Tuple	     =       start_length + max_new_tokens





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return input_ids.shape[-1] >= self.max_length



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       max_time
       UpperCamelCase     : Dict	     =       time.time() if initial_timestamp is None else initial_timestamp





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return time.time() - self.initial_timestamp > self.max_time



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return any(criteria(A_	,							A_       ) for criteria in self       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for stopping_criterium in self:
        if isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
        elif isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
       return None



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase					)						->			StoppingCriteriaList:
 UpperCamelCase     : Tuple	     =       stopping_criteria.max_length
 UpperCamelCase     : Union[str, Any]	     =       deepcopy(_lowerCAmelCase					)
 if stopping_max_length is not None and stopping_max_length != max_length:
  warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"							,       _lowerCAmelCase					)
 elif stopping_max_length is None:
  new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCAmelCase					)					)
 return new_stopping_criteria
