


'''simple docstring'''






import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


a_    :			Any      				=			logging.get_logger(__name__)






def 		_A (lowerCAmelCase__     :Dict=None ,  lowerCAmelCase__     :Dict=None						)      ->     List[str]:




     '''simple docstring'''



     return field(default_factory=lambda: default ,  metadata=__UpperCAmelCase						)






@dataclass
class        a   :
 _lowerCAmelCase           =		list_field(
     default=[]     , metadata={
         """help""": (
             """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
             """ of all available models"""
         )
     }     , )

 _lowerCAmelCase           =		list_field(
     default=[8]     , metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}				)

 _lowerCAmelCase           =		list_field(
     default=[8, 3_2, 1_2_8, 5_1_2]     , metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""}     , )

 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""}     , )
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""}     , )
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Use FP16 to accelerate inference."""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Benchmark training of model"""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Verbose memory tracing"""}				)
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""}     , )
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={
         """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
     }     , )
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Trace memory line by line"""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Save result to a CSV file"""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Save all print statements in a log file"""}				)
 _lowerCAmelCase           =		field(default=_UpperCAmelCase     , metadata={"""help""": """Whether to print environment information"""}				)
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={
         """help""": (
             """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
             """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
             """ for debugging / testing and on TPU."""
         )
     }     , )
 _lowerCAmelCase           =		field(
     default=f'''inference_time_{round(time()				)}.csv'''     , metadata={"""help""": """CSV filename used if saving time results to csv."""}     , )
 _lowerCAmelCase           =		field(
     default=f'''inference_memory_{round(time()				)}.csv'''     , metadata={"""help""": """CSV filename used if saving memory results to csv."""}     , )
 _lowerCAmelCase           =		field(
     default=f'''train_time_{round(time()				)}.csv'''     , metadata={"""help""": """CSV filename used if saving time results to csv for training."""}     , )
 _lowerCAmelCase           =		field(
     default=f'''train_memory_{round(time()				)}.csv'''     , metadata={"""help""": """CSV filename used if saving memory results to csv for training."""}     , )
 _lowerCAmelCase           =		field(
     default=f'''env_info_{round(time()				)}.csv'''     , metadata={"""help""": """CSV filename used if saving environment information."""}     , )
 _lowerCAmelCase           =		field(
     default=f'''log_{round(time()				)}.csv'''     , metadata={"""help""": """Log filename used if print statements are saved in log."""}     , )
 _lowerCAmelCase           =		field(default=3     , metadata={"""help""": """Times an experiment will be run."""}				)
 _lowerCAmelCase           =		field(
     default=_UpperCAmelCase     , metadata={
         """help""": (
             """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
             """ model weights."""
         )
     }     , )
 def 							__UpperCAmelCase						(       self  )    ->							Optional[int]:
      warnings.warn(
          f'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
          ' are deprecated in general and it is advised to use external Benchmarking libraries '
          ' to benchmark Transformer models.'					, _UpperCAmelCase					, )
 def 							__UpperCAmelCase						(       self  )    ->							List[str]:
      return json.dumps(dataclasses.asdict(self  )					, indent=2  )
 @property
 def 							__UpperCAmelCase						(       self  )    ->							Union[str, Any]:
      if len(self.models  ) <= 0:
           raise ValueError(
               'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
               ' bert-base-cased` or `args.models = [\'bert-base-cased\'].'  )
      return self.models




 @property
 def 							__UpperCAmelCase						(       self  )    ->							Tuple:
      if not self.multi_process:
           return False
      elif self.is_tpu:
           logger.info('Multiprocessing is currently not possible on TPU.'  )
           return False
      else:
           return True


"""simple docstring"""






from jiwer import compute_measures

import datasets


__A			   = "\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n"

__A			   = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe 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.\n\nThis 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.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

__A			   = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,_KWARGS_DESCRIPTION  )
class     UpperCAmelCase						(datasets.Metric  ):



    """simple docstring"""

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