






'''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


__A							:							Union[str, Any]  							=		""""""


if version.parse(importlib_metadata.version("""jiwer""")) < version.parse("""2.3.0"""):
 class 				lowercase       (							tr.AbstractTransform      ):


     '''simple docstring'''

     def __init__(					self     :     str				,     __lowerCamelCase     :     str = " "     )							->							Optional[Any]:

      '''simple docstring'''




      lowerCamelCase__  =     sentence_delimiter

     def    a__				(					self     :     Any				,     __lowerCamelCase     :     str     )							->							Any:

      '''simple docstring'''




      return list(__lowerCamelCase     )




     def    a__				(					self     :     str				,     __lowerCamelCase     :     List[str]     )							->							Dict:

      '''simple docstring'''




      lowerCamelCase__  =     []
      for sent_idx, sentence in enumerate(__lowerCamelCase     ):
       chars.extend(self.process_string(__lowerCamelCase     )     )
       if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowerCamelCase     ) - 1:
        chars.append(self.sentence_delimiter     )
      return chars
 __A							:							Any  							=		tr.Compose(
     [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
 )
else:
 __A							:							Optional[int]  							=		tr.Compose(
     [
         tr.RemoveMultipleSpaces(),
         tr.Strip(),
         tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
         tr.ReduceToListOfListOfChars(),
     ]
 )


__A							:							int  							=		"""\
@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.}
}
"""

__A							:							int  							=		"""\
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.
"""

__A							:							str  							=		"""
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 				lowercase       (							datasets.Metric      ):


    '''simple docstring'''

    def    a__				(					self     :     str     )							->							List[Any]:

     '''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    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Any=False     )							->							Dict:

     '''simple docstring'''




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

     lowerCamelCase__  =     0
     lowerCamelCase__  =     0
     for prediction, reference in zip(__lowerCamelCase				,     __lowerCamelCase     ):
      lowerCamelCase__  =     jiwer.compute_measures(
          __lowerCamelCase				,     __lowerCamelCase				,     truth_transform=__lowerCamelCase				,     hypothesis_transform=__lowerCamelCase				,     )
      incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
      total += measures["substitutions"] + measures["deletions"] + measures["hits"]

     return incorrect / total









'''simple docstring'''





import tensorflow as tf

from ...tf_utils import shape_list
class 				lowercase       (							tf.keras.layers.Layer      ):


    '''simple docstring'''

    def __init__(					self     :     Union[str, Any]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     int=1				,     __lowerCamelCase     :     Tuple=False				,     **__lowerCamelCase     :     Dict     )							->							str:

     '''simple docstring'''




     super().__init__(**__lowerCamelCase     )

     lowerCamelCase__  =     vocab_size
     lowerCamelCase__  =     d_embed
     lowerCamelCase__  =     d_proj

     lowerCamelCase__  =     cutoffs + [vocab_size]
     lowerCamelCase__  =     [0] + self.cutoffs
     lowerCamelCase__  =     div_val

     lowerCamelCase__  =     self.cutoffs[0]
     lowerCamelCase__  =     len(self.cutoffs     ) - 1
     lowerCamelCase__  =     self.shortlist_size + self.n_clusters
     lowerCamelCase__  =     keep_order

     lowerCamelCase__  =     []
     lowerCamelCase__  =     []

    def    a__				(					self     :     Optional[int]				,     __lowerCamelCase     :     str     )							->							List[str]:

     '''simple docstring'''




     if self.n_clusters > 0:
      lowerCamelCase__  =     self.add_weight(
          shape=(self.n_clusters, self.d_embed)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name="cluster_weight"     )
      lowerCamelCase__  =     self.add_weight(
          shape=(self.n_clusters,)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name="cluster_bias"     )

     if self.div_val == 1:
      for i in range(len(self.cutoffs     )     ):
       if self.d_proj != self.d_embed:
        lowerCamelCase__  =     self.add_weight(
            shape=(self.d_embed, self.d_proj)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_projs_._{i}'''				,     )
        self.out_projs.append(__lowerCamelCase     )
       else:
        self.out_projs.append(__lowerCamelCase     )
       lowerCamelCase__  =     self.add_weight(
           shape=(self.vocab_size, self.d_embed)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_layers_._{i}_._weight'''				,     )
       lowerCamelCase__  =     self.add_weight(
           shape=(self.vocab_size,)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_layers_._{i}_._bias'''				,     )
       self.out_layers.append((weight, bias)     )
     else:
      for i in range(len(self.cutoffs     )     ):
       lowerCamelCase__  ,	lowerCamelCase__  =     self.cutoff_ends[i], self.cutoff_ends[i + 1]
       lowerCamelCase__  =     self.d_embed // (self.div_val**i)

       lowerCamelCase__  =     self.add_weight(
           shape=(d_emb_i, self.d_proj)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_projs_._{i}'''     )
       self.out_projs.append(__lowerCamelCase     )
       lowerCamelCase__  =     self.add_weight(
           shape=(r_idx - l_idx, d_emb_i)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_layers_._{i}_._weight'''				,     )
       lowerCamelCase__  =     self.add_weight(
           shape=(r_idx - l_idx,)				,     initializer="zeros"				,     trainable=__lowerCamelCase				,     name=f'''out_layers_._{i}_._bias'''				,     )
       self.out_layers.append((weight, bias)     )
     super().build(__lowerCamelCase     )

    @staticmethod
    def    a__				(					__lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     List[str]=None     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     x
     if proj is not None:
      lowerCamelCase__  =     tf.einsum("ibd,ed->ibe"				,     __lowerCamelCase				,     __lowerCamelCase     )
     return tf.einsum("ibd,nd->ibn"				,     __lowerCamelCase				,     __lowerCamelCase     ) + b

    @staticmethod
    def    a__				(					__lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Union[str, Any]     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     shape_list(__lowerCamelCase     )
     lowerCamelCase__  =     tf.range(lp_size[0]				,     dtype=target.dtype     )
     lowerCamelCase__  =     tf.stack([r, target]				,     1     )
     return tf.gather_nd(__lowerCamelCase				,     __lowerCamelCase     )




    def    a__				(					self     :     Any				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     str=True				,     __lowerCamelCase     :     Tuple=False     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  =     0
     if self.n_clusters == 0:
      lowerCamelCase__  =     self._logit(__lowerCamelCase				,     self.out_layers[0][0]				,     self.out_layers[0][1]				,     self.out_projs[0]     )
      if target is not None:
       lowerCamelCase__  =     tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__lowerCamelCase				,     logits=__lowerCamelCase     )
      lowerCamelCase__  =     tf.nn.log_softmax(__lowerCamelCase				,     axis=-1     )
     else:
      lowerCamelCase__  =     shape_list(__lowerCamelCase     )
      lowerCamelCase__  =     []
      lowerCamelCase__  =     tf.zeros(hidden_sizes[:2]     )
      for i in range(len(self.cutoffs     )     ):
       lowerCamelCase__  ,	lowerCamelCase__  =     self.cutoff_ends[i], self.cutoff_ends[i + 1]
       if target is not None:
        lowerCamelCase__  =     (target >= l_idx) & (target < r_idx)
        lowerCamelCase__  =     tf.where(__lowerCamelCase     )
        lowerCamelCase__  =     tf.boolean_mask(__lowerCamelCase				,     __lowerCamelCase     ) - l_idx

       if self.div_val == 1:
        lowerCamelCase__  =     self.out_layers[0][0][l_idx:r_idx]
        lowerCamelCase__  =     self.out_layers[0][1][l_idx:r_idx]
       else:
        lowerCamelCase__  =     self.out_layers[i][0]
        lowerCamelCase__  =     self.out_layers[i][1]

       if i == 0:
        lowerCamelCase__  =     tf.concat([cur_W, self.cluster_weight]				,     0     )
        lowerCamelCase__  =     tf.concat([cur_b, self.cluster_bias]				,     0     )

        lowerCamelCase__  =     self._logit(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     self.out_projs[0]     )
        lowerCamelCase__  =     tf.nn.log_softmax(__lowerCamelCase     )
        out.append(head_logprob[..., : self.cutoffs[0]]     )
        if target is not None:
         lowerCamelCase__  =     tf.boolean_mask(__lowerCamelCase				,     __lowerCamelCase     )
         lowerCamelCase__  =     self._gather_logprob(__lowerCamelCase				,     __lowerCamelCase     )
       else:
        lowerCamelCase__  =     self._logit(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     self.out_projs[i]     )
        lowerCamelCase__  =     tf.nn.log_softmax(__lowerCamelCase     )
        lowerCamelCase__  =     self.cutoffs[0] + i - 1  # No probability for the head cluster
        lowerCamelCase__  =     head_logprob[..., cluster_prob_idx, None] + tail_logprob
        out.append(__lowerCamelCase     )
        if target is not None:
         lowerCamelCase__  =     tf.boolean_mask(__lowerCamelCase				,     __lowerCamelCase     )
         lowerCamelCase__  =     tf.boolean_mask(__lowerCamelCase				,     __lowerCamelCase     )
         lowerCamelCase__  =     self._gather_logprob(__lowerCamelCase				,     __lowerCamelCase     )
         cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
       if target is not None:
        loss += tf.scatter_nd(__lowerCamelCase				,     -cur_logprob				,     shape_list(__lowerCamelCase     )     )
      lowerCamelCase__  =     tf.concat(__lowerCamelCase				,     axis=-1     )

     if target is not None:
      if return_mean:
       lowerCamelCase__  =     tf.reduce_mean(__lowerCamelCase     )
      # Add the training-time loss value to the layer using `self.add_loss()`.
      self.add_loss(__lowerCamelCase     )

      # Log the loss as a metric (we could log arbitrary metrics,
      # including different metrics for training and inference.
      self.add_metric(__lowerCamelCase				,     name=self.name				,     aggregation="mean" if return_mean else ""     )

     return out

