





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







from typing import Callable, Dict, Optional, Tuple

import torch
from torch import nn
from torch.distributions import (
    AffineTransform,
    Distribution,
    Independent,
    NegativeBinomial,
    Normal,
    StudentT,
    TransformedDistribution,
)



class  A__       (	__snake_case      ):





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




       UpperCamelCase     : Union[str, Any]	     =       1.0 if scale is None else scale
       UpperCamelCase     : Optional[int]	     =       0.0 if loc is None else loc

       super().__init__(A_	,							[AffineTransform(loc=self.loc	,							scale=self.scale	,							event_dim=A_       )]       )





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




       return self.base_dist.mean * self.scale + self.loc





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




       return self.base_dist.variance * self.scale**2





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




       return self.variance.sqrt()



class  A__       (	nn.Module      ):





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




       super().__init__(**A_       )
       UpperCamelCase     : Union[str, Any]	     =       args_dim
       UpperCamelCase     : str	     =       nn.ModuleList([nn.Linear(A_	,							A_       ) for dim in args_dim.values()]       )
       UpperCamelCase     : Union[str, Any]	     =       domain_map





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




       UpperCamelCase     : List[Any]	     =       [proj(A_       ) for proj in self.proj]

       return self.domain_map(*A_       )



class  A__       (	nn.Module      ):





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




       super().__init__()
       UpperCamelCase     : str	     =       function





      def 	__UpperCamelCase(			self	,							A_	,							*A_       ):
       '''simple docstring'''




       return self.function(A_	,							*A_       )



class  A__       :
      _UpperCAmelCase     :type
      _UpperCAmelCase     :int
      _UpperCAmelCase     :Dict[str, int]





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




       UpperCamelCase     : Tuple	     =       dim
       UpperCamelCase     : Union[str, Any]	     =       {k: dim * self.args_dim[k] for k in self.args_dim}





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




       if self.dim == 1:
        return self.distribution_class(*A_       )
       else:
        return Independent(self.distribution_class(*A_       )	,							1       )





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




       UpperCamelCase     : str	     =       self._base_distribution(A_       )
       if loc is None and scale is None:
        return distr
       else:
        return AffineTransformed(A_	,							loc=A_	,							scale=A_	,							event_dim=self.event_dim       )





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




       return () if self.dim == 1 else (self.dim,)





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




       return len(self.event_shape       )





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




       return 0.0





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




       return ParameterProjection(
           in_features=A_	,							args_dim=self.args_dim	,							domain_map=LambdaLayer(self.domain_map       )	,							)





      def 	__UpperCamelCase(			self	,							*A_       ):
       '''simple docstring'''




       raise NotImplementedError()





      @staticmethod
      def 	__UpperCamelCase(			A_       ):
       '''simple docstring'''




       return (x + torch.sqrt(torch.square(A_       ) + 4.0       )) / 2.0



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"df": 1, "loc": 1, "scale": 1}
      _UpperCAmelCase     :type						   =       StudentT





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       cls.squareplus(A_       ).clamp_min(torch.finfo(scale.dtype       ).eps       )
       UpperCamelCase     : int	     =       2.0 + cls.squareplus(A_       )
       return df.squeeze(-1       ), loc.squeeze(-1       ), scale.squeeze(-1       )



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"loc": 1, "scale": 1}
      _UpperCAmelCase     :type						   =       Normal





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       cls.squareplus(A_       ).clamp_min(torch.finfo(scale.dtype       ).eps       )
       return loc.squeeze(-1       ), scale.squeeze(-1       )



class  A__       (	__snake_case      ):
      _UpperCAmelCase     :Dict[str, int]						   =       {"total_count": 1, "logits": 1}
      _UpperCAmelCase     :type						   =       NegativeBinomial





      @classmethod
      def 	__UpperCamelCase(			cls	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       cls.squareplus(A_       )
       return total_count.squeeze(-1       ), logits.squeeze(-1       )





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




       UpperCamelCase     ,   UpperCamelCase     : Optional[int]	     =       distr_args
       if self.dim == 1:
        return self.distribution_class(total_count=A_	,							logits=A_       )
       else:
        return Independent(self.distribution_class(total_count=A_	,							logits=A_       )	,							1       )





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




       UpperCamelCase     ,   UpperCamelCase     : Any	     =       distr_args

       if scale is not None:
        # See scaling property of Gamma.
        logits += scale.log()

       return self._base_distribution((total_count, logits)       )
