





'''simple docstring'''






from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
      import tensorflow as tf


A__							:  Optional[Any]    =logging.get_logger(__name__)




@dataclass
class 					UpperCAmelCase	(     snake_case_  ):
      _lowercase:     Optional[int]			=  [
          '''no_inference''',
          '''no_cuda''',
          '''no_tpu''',
          '''no_speed''',
          '''no_memory''',
          '''no_env_print''',
          '''no_multi_process''',
      ]




      def __init__(     self     :					Any     ,     **__snake_case     :					Any    )							-> Tuple:
            for deprecated_arg in self.deprecated_args:
                  if deprecated_arg in kwargs:
                        _lowerCAmelCase					=				deprecated_arg[3:]
                        _lowerCAmelCase					=				not kwargs.pop(__snake_case    )
                        logger.warning(
                            f"{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"
                            f" {positive_arg}={kwargs[positive_arg]}"    )
            _lowerCAmelCase					=				kwargs.pop("""tpu_name"""     ,     self.tpu_name    )
            _lowerCAmelCase					=				kwargs.pop("""device_idx"""     ,     self.device_idx    )
            _lowerCAmelCase					=				kwargs.pop("""eager_mode"""     ,     self.eager_mode    )
            _lowerCAmelCase					=				kwargs.pop("""use_xla"""     ,     self.use_xla    )
            super().__init__(**__snake_case    )

      _lowercase:     str			=  field(
          default=snake_case_				,						metadata={'''help''': '''Name of TPU'''}				,						)
      _lowercase:     int			=  field(
          default=0				,						metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}				,						)
      _lowercase:     bool			=  field(default=snake_case_				,						metadata={'''help''': '''Benchmark models in eager model.'''}  )
      _lowercase:     bool			=  field(
          default=snake_case_				,						metadata={
              '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
          }				,						)




      @cached_property
      def 							lowercase__       (     self     :					Optional[Any]    )							-> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]:
            requires_backends(self     ,     ["""tf"""]    )
            _lowerCAmelCase					=				None
            if self.tpu:
                  try:
                        if self.tpu_name:
                              _lowerCAmelCase					=				tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name    )
                        else:
                              _lowerCAmelCase					=				tf.distribute.cluster_resolver.TPUClusterResolver()
                  except ValueError:
                        _lowerCAmelCase					=				None
            return tpu




      @cached_property
      def 							lowercase__       (     self     :					List[str]    )							-> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]:
            requires_backends(self     ,     ["""tf"""]    )
            if self.is_tpu:
                  tf.config.experimental_connect_to_cluster(self._setup_tpu    )
                  tf.tpu.experimental.initialize_tpu_system(self._setup_tpu    )

                  _lowerCAmelCase					=				tf.distribute.TPUStrategy(self._setup_tpu    )
            else:
                  # currently no multi gpu is allowed
                  if self.is_gpu:
                        # TODO: Currently only single GPU is supported
                        tf.config.set_visible_devices(self.gpu_list[self.device_idx]     ,     """GPU"""    )
                        _lowerCAmelCase					=				tf.distribute.OneDeviceStrategy(device=f"/gpu:{self.device_idx}"    )
                  else:
                        tf.config.set_visible_devices([]     ,     """GPU"""    )  # disable GPU
                        _lowerCAmelCase					=				tf.distribute.OneDeviceStrategy(device=f"/cpu:{self.device_idx}"    )

            return strategy




      @property
      def 							lowercase__       (     self     :					Dict    )							-> bool:
            requires_backends(self     ,     ["""tf"""]    )
            return self._setup_tpu is not None




      @property
      def 							lowercase__       (     self     :					Dict    )							-> "tf.distribute.Strategy":
            requires_backends(self     ,     ["""tf"""]    )
            return self._setup_strategy




      @property
      def 							lowercase__       (     self     :					List[str]    )							-> Tuple:
            requires_backends(self     ,     ["""tf"""]    )
            return tf.config.list_physical_devices("""GPU"""    )




      @property
      def 							lowercase__       (     self     :					Optional[Any]    )							-> int:
            requires_backends(self     ,     ["""tf"""]    )
            if self.cuda:
                  return len(self.gpu_list    )
            return 0




      @property
      def 							lowercase__       (     self     :					Optional[int]    )							-> bool:
            return self.n_gpu > 0













'''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__							:  Dict    =''''''


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




      class 					UpperCAmelCase	(     tr.AbstractTransform  ):




            def __init__(     self     :					Any     ,     __snake_case     :					str = " "    )							-> Any:
                  _lowerCAmelCase					=				sentence_delimiter




            def 							lowercase__       (     self     :					str     ,     __snake_case     :					str    )							-> Optional[int]:
                  return list(__snake_case    )




            def 							lowercase__       (     self     :					Tuple     ,     __snake_case     :					List[str]    )							-> Union[str, Any]:
                  _lowerCAmelCase					=				[]
                  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




      A__							:  Optional[Any]    =tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      A__							:  Tuple    =tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


A__							:  List[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.}
}
'''

A__							:  Optional[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__							:  List[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 					UpperCAmelCase	(     datasets.Metric  ):




      def 							lowercase__       (     self     :					Any    )							-> Dict:
            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     :					Optional[Any]     ,     __snake_case     :					Optional[Any]     ,     __snake_case     :					List[str]     ,     __snake_case     :					Tuple=False    )							-> List[Any]:
            if concatenate_texts:
                  return jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )["wer"]

            _lowerCAmelCase					=				0
            _lowerCAmelCase					=				0
            for prediction, reference in zip(__snake_case     ,     __snake_case    ):
                  _lowerCAmelCase					=				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






