


"""simple docstring"""
from jiwer import compute_measures

import datasets


UpperCAmelCase				=						"""\
@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.}
}
"""

UpperCAmelCase				=						"""\
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.
"""

UpperCAmelCase				=						"""
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 	lowercase__				(					datasets.Metric				):





   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      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      ,   SCREAMING_SNAKE_CASE=None      ,   SCREAMING_SNAKE_CASE=None      ,   SCREAMING_SNAKE_CASE=False)  ->  Union[str, Any]:
      if concatenate_texts:
         return compute_measures(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)["wer"]
      else:
         _lowerCamelCase	:					List[str]   =		0
         _lowerCamelCase	:					List[Any]   =		0
         for prediction, reference in zip(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE):
            _lowerCamelCase	:					Union[str, Any]   =		compute_measures(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)
            incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
            total += measures["substitutions"] + measures["deletions"] + measures["hits"]
         return incorrect / total





"""simple docstring"""
import mpmath  # for roots of unity
import numpy as np




class 	lowercase__				:





   def __init__(							self      ,   SCREAMING_SNAKE_CASE=None      ,   SCREAMING_SNAKE_CASE=None)  ->  Tuple:
      # Input as list
      _lowerCamelCase	:					Any   =		list(poly_a or [0])[:]
      _lowerCamelCase	:					Optional[Any]   =		list(poly_b or [0])[:]

      # Remove leading zero coefficients
      while self.polyA[-1] == 0:
         self.polyA.pop()
      _lowerCamelCase	:					int   =		len(self.polyA)

      while self.polyB[-1] == 0:
         self.polyB.pop()
      _lowerCamelCase	:					Union[str, Any]   =		len(self.polyB)

      # Add 0 to make lengths equal a power of 2
      _lowerCamelCase	:					List[Any]   =		int(
          2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1)))

      while len(self.polyA) < self.c_max_length:
         self.polyA.append(0)
      while len(self.polyB) < self.c_max_length:
         self.polyB.append(0)
      # A complex root used for the fourier transform
      _lowerCamelCase	:					Optional[Any]   =		complex(mpmath.root(x=1      ,   n=self.c_max_length      ,   k=1))

      # The product
      _lowerCamelCase	:					int   =		self.__multiply()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE)  ->  List[str]:
      _lowerCamelCase	:					Dict   =		[[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB]
      # Corner case
      if len(SCREAMING_SNAKE_CASE) <= 1:
         return dft[0]
      #
      _lowerCamelCase	:					str   =		self.c_max_length // 2
      while next_ncol > 0:
         _lowerCamelCase	:					Dict   =		[[] for i in range(SCREAMING_SNAKE_CASE)]
         _lowerCamelCase	:					Tuple   =		self.root**next_ncol

         # First half of next step
         _lowerCamelCase	:					int   =		1
         for j in range(self.c_max_length // (next_ncol * 2)):
            for i in range(SCREAMING_SNAKE_CASE):
               new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
            current_root *= root
         # Second half of next step
         _lowerCamelCase	:					Optional[int]   =		1
         for j in range(self.c_max_length // (next_ncol * 2)):
            for i in range(SCREAMING_SNAKE_CASE):
               new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
            current_root *= root
         # Update
         _lowerCamelCase	:					Union[str, Any]   =		new_dft
         _lowerCamelCase	:					List[str]   =		next_ncol // 2
      return dft[0]





   def 		UpperCamelCase_  (							self)  ->  str:
      _lowerCamelCase	:					Optional[Any]   =		self.__dft("""A""")
      _lowerCamelCase	:					List[str]   =		self.__dft("""B""")
      _lowerCamelCase	:					List[Any]   =		[[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
      del dft_a
      del dft_b

      # Corner Case
      if len(inverce_c[0]) <= 1:
         return inverce_c[0]
      # Inverse DFT
      _lowerCamelCase	:					List[str]   =		2
      while next_ncol <= self.c_max_length:
         _lowerCamelCase	:					Any   =		[[] for i in range(SCREAMING_SNAKE_CASE)]
         _lowerCamelCase	:					List[Any]   =		self.root ** (next_ncol // 2)
         _lowerCamelCase	:					str   =		1
         # First half of next step
         for j in range(self.c_max_length // next_ncol):
            for i in range(next_ncol // 2):
               # Even positions
               new_inverse_c[i].append(
                   (
                       inverce_c[i][j]
                       + inverce_c[i][j + self.c_max_length // next_ncol]
                   )
                   / 2)
               # Odd positions
               new_inverse_c[i + next_ncol // 2].append(
                   (
                       inverce_c[i][j]
                       - inverce_c[i][j + self.c_max_length // next_ncol]
                   )
                   / (2 * current_root))
            current_root *= root
         # Update
         _lowerCamelCase	:					Any   =		new_inverse_c
         next_ncol *= 2
      # Unpack
      _lowerCamelCase	:					Optional[Any]   =		[round(x[0].real      ,   8) + round(x[0].imag      ,   8) * 1j for x in inverce_c]

      # Remove leading 0's
      while inverce_c[-1] == 0:
         inverce_c.pop()
      return inverce_c





   def __str__(							self)  ->  Any:
      _lowerCamelCase	:					Dict   =		"""A = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A]))
      _lowerCamelCase	:					List[Any]   =		"""B = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B]))
      _lowerCamelCase	:					int   =		"""A*B = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.product))

      return F'{a}\n{b}\n{c}'


# Unit tests
if __name__ == "__main__":
 import doctest

 doctest.testmod()

