



'''simple docstring'''





from jiwer import compute_measures

import datasets


_lowerCAmelCase      						=	'''\
@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      						=	'''\
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      						=	'''
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        lowerCAmelCase_(				datasets.Metric     ):
  '''simple docstring'''




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







'''simple docstring'''





import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow






class        lowerCAmelCase_:
  '''simple docstring'''




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Optional[Any]:
      return None







class        lowerCAmelCase_:
  '''simple docstring'''




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Tuple:
      return None







class        lowerCAmelCase_(				unittest.TestCase     ):
  '''simple docstring'''




  __lowercase							:      Dict				=      [
      # (model_name, model_kwargs)
      ('''bert-base-cased''', {}),
      ('''gpt2''', {'''use_cache''': False}),  # We don't support exporting GPT2 past keys anymore
  ]




  @require_tf
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		int:
      for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
          self._test_export(__UpperCAmelCase  ,"""tf"""  ,12  ,**__UpperCAmelCase      )




  @require_torch
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
          self._test_export(__UpperCAmelCase  ,"""pt"""  ,12  ,**__UpperCAmelCase      )




  @require_torch
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Any:
      from transformers import BertModel

      lowerCAmelCase__ :  Optional[int]							      =					["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""]
      with NamedTemporaryFile(mode="""w+t"""      ) as vocab_file:
          vocab_file.write("""\n""".join(__UpperCAmelCase      )      )
          vocab_file.flush()
          lowerCAmelCase__ :  Dict							      =					BertTokenizerFast(vocab_file.name      )

      with TemporaryDirectory() as bert_save_dir:
          lowerCAmelCase__ :  Tuple							      =					BertModel(BertConfig(vocab_size=len(__UpperCAmelCase      )      )      )
          model.save_pretrained(__UpperCAmelCase      )
          self._test_export(__UpperCAmelCase  ,"""pt"""  ,12  ,__UpperCAmelCase      )




  @require_tf
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		List[str]:
      for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
          lowerCAmelCase__ :  Dict							      =					self._test_export(__UpperCAmelCase  ,"""tf"""  ,12  ,**__UpperCAmelCase      )
          lowerCAmelCase__ :  List[str]							      =					quantize(Path(__UpperCAmelCase      )      )

          # Ensure the actual quantized model is not bigger than the original one
          if quantized_path.stat().st_size >= Path(__UpperCAmelCase      ).stat().st_size:
              self.fail("""Quantized model is bigger than initial ONNX model"""      )




  @require_torch
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		List[Any]:
      for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
          lowerCAmelCase__ :  Any							      =					self._test_export(__UpperCAmelCase  ,"""pt"""  ,12  ,**__UpperCAmelCase      )
          lowerCAmelCase__ :  Dict							      =					quantize(__UpperCAmelCase      )

          # Ensure the actual quantized model is not bigger than the original one
          if quantized_path.stat().st_size >= Path(__UpperCAmelCase      ).stat().st_size:
              self.fail("""Quantized model is bigger than initial ONNX model"""      )




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase=None  ,**__UpperCAmelCase      )    ->		Optional[Any]:
      try:
          # Compute path
          with TemporaryDirectory() as tempdir:
              lowerCAmelCase__ :  Optional[int]							      =					Path(__UpperCAmelCase      ).joinpath("""model.onnx"""      )

          # Remove folder if exists
          if path.parent.exists():
              path.parent.rmdir()

          # Export
          convert(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,**__UpperCAmelCase      )

          return path
      except Exception as e:
          self.fail(__UpperCAmelCase      )




  @require_torch
  @require_tokenizers
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      from transformers import BertModel

      lowerCAmelCase__ :  List[Any]							      =					BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""      )      )
      lowerCAmelCase__ :  Union[str, Any]							      =					BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""      )
      self._test_infer_dynamic_axis(__UpperCAmelCase  ,__UpperCAmelCase  ,"""pt"""      )




  @require_tf
  @require_tokenizers
  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      from transformers import TFBertModel

      lowerCAmelCase__ :  int							      =					TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""      )      )
      lowerCAmelCase__ :  Optional[int]							      =					BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""      )
      self._test_infer_dynamic_axis(__UpperCAmelCase  ,__UpperCAmelCase  ,"""tf"""      )




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Tuple:
      lowerCAmelCase__ :  Any							      =					FeatureExtractionPipeline(__UpperCAmelCase  ,__UpperCAmelCase      )

      lowerCAmelCase__ :  List[str]							      =					["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""]
      lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  Union[str, Any]							      =					infer_shapes(__UpperCAmelCase  ,__UpperCAmelCase      )

      # Assert all variables are present
      self.assertEqual(len(__UpperCAmelCase      )  ,len(__UpperCAmelCase      )      )
      self.assertTrue(all(var_name in shapes for var_name in variable_names      )      )
      self.assertSequenceEqual(variable_names[:3]  ,__UpperCAmelCase      )
      self.assertSequenceEqual(variable_names[3:]  ,__UpperCAmelCase      )

      # Assert inputs are {0: batch, 1: sequence}
      for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
          self.assertDictEqual(shapes[var_name]  ,{0: """batch""", 1: """sequence"""}      )

      # Assert outputs are {0: batch, 1: sequence} and {0: batch}
      self.assertDictEqual(shapes["""output_0"""]  ,{0: """batch""", 1: """sequence"""}      )
      self.assertDictEqual(shapes["""output_1"""]  ,{0: """batch"""}      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__ :  List[str]							      =					["""input_ids""", """attention_mask""", """token_type_ids"""]
      lowerCAmelCase__ :  Union[str, Any]							      =					{"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]}
      lowerCAmelCase__      ,   lowerCAmelCase__ :  List[Any]							      =					ensure_valid_input(FuncContiguousArgs()  ,__UpperCAmelCase  ,__UpperCAmelCase      )

      # Should have exactly the same number of args (all are valid)
      self.assertEqual(len(__UpperCAmelCase      )  ,3      )

      # Should have exactly the same input names
      self.assertEqual(set(__UpperCAmelCase      )  ,set(__UpperCAmelCase      )      )

      # Parameter should be reordered according to their respective place in the function:
      # (input_ids, token_type_ids, attention_mask)
      self.assertEqual(__UpperCAmelCase  ,(tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""])      )

      # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
      lowerCAmelCase__      ,   lowerCAmelCase__ :  int							      =					ensure_valid_input(FuncNonContiguousArgs()  ,__UpperCAmelCase  ,__UpperCAmelCase      )

      # Should have exactly the one arg (all before the one not provided "some_other_args")
      self.assertEqual(len(__UpperCAmelCase      )  ,1      )
      self.assertEqual(len(__UpperCAmelCase      )  ,1      )

      # Should have only "input_ids"
      self.assertEqual(inputs_args[0]  ,tokens["""input_ids"""]      )
      self.assertEqual(ordered_input_names[0]  ,"""input_ids"""      )






  def 							UpperCAmelCase_	(    self      )    ->		Tuple:
      lowerCAmelCase__ :  Dict							      =					generate_identified_filename(Path("""/home/something/my_fake_model.onnx"""      )  ,"""-test"""      )
      self.assertEqual("""/home/something/my_fake_model-test.onnx"""  ,generated.as_posix()      )


