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   :     Tuple       =				""


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


      class      lowerCamelCase    (tr.AbstractTransform    ):
        """simple docstring"""







        def __init__(							self       :				Tuple     ,   __magic_name__       :				str = " "      )     ->		Optional[int]:
              SCREAMING_SNAKE_CASE_      =     sentence_delimiter







        def       __A   (							self       :				List[Any]     ,   __magic_name__       :				str      )     ->		Dict:
              return list(__magic_name__      )







        def       __A   (							self       :				str     ,   __magic_name__       :				List[str]      )     ->		List[Any]:
              SCREAMING_SNAKE_CASE_      =     []
              for sent_idx, sentence in enumerate(__magic_name__      ):
                    chars.extend(self.process_string(__magic_name__      )      )
                    if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__magic_name__      ) - 1:
                          chars.append(self.sentence_delimiter      )
              return chars



      A   :     int       =				tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      A   :     str       =				tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


A   :     Tuple       =				"\\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   :     int       =				"\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (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 characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER'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\nperformance of the ASR system with a CER of 0 being a perfect score.\n"

A   :     str       =				"\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character 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    >>> cer = datasets.load_metric(\"cer\")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n"


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,					_KWARGS_DESCRIPTION    )
class      lowerCamelCase    (datasets.Metric    ):
  """simple docstring"""







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

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

        return incorrect / total



import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A   :     Tuple       =				DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A   :     Dict       =				"main"
# Default branch name
A   :     List[str]       =				"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
A   :     Tuple       =				"aaaaaaa"
# This commit does not exist, so we should 404.

A   :     int       =				"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
A   :     Tuple       =				"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def    a__       (						):
      print("Welcome!" )
      yield
      print("Bye!" )


@contextlib.contextmanager
def    a__       (						):
      print("Bonjour!" )
      yield
      print("Au revoir!" )


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Any:
        # If the spec is missing, importlib would not be able to import the module dynamically.
        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"      ) is not None



class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		Union[str, Any]:
        with ContextManagers([]      ):
              print("Transformers are awesome!"      )
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()     ,   "Transformers are awesome!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Dict     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        with ContextManagers([context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Welcome!\nTransformers are awesome!\nBye!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				str      )     ->		Union[str, Any]:
        with ContextManagers([context_fr(), context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )







  @require_torch
  def       __A   (							self       :				List[str]      )     ->		Union[str, Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_tf
  def       __A   (							self       :				List[str]      )     ->		Optional[Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_flax
  def       __A   (							self       :				int      )     ->		Tuple:
        # Flax models don't have labels
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


