


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


UpperCamelCase								=	""""""


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






     class   _lowerCamelCase (					tr.AbstractTransform			):




            """simple docstring"""



            def __init__(      self				,       _SCREAMING_SNAKE_CASE = " "		)->int:




              '''simple docstring'''





              A_      :				int		     =					sentence_delimiter



            def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->Union[str, Any]:




              '''simple docstring'''





              return list(_SCREAMING_SNAKE_CASE		)







            def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE		)->List[Any]:




              '''simple docstring'''





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




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


UpperCamelCase								=	"""\
@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.}
}
"""

UpperCamelCase								=	"""\
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.
"""

UpperCamelCase								=	"""
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   _lowerCamelCase (					datasets.Metric			):




       """simple docstring"""



       def        _snake_case       (      self		)->Dict:




         '''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        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=False		)->Optional[Any]:




         '''simple docstring'''





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

         A_      :				Dict		     =					0
         A_      :				List[Any]		     =					0
         for prediction, reference in zip(_SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE		):
           A_      :				int		     =					jiwer.compute_measures(
               _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       truth_transform=_SCREAMING_SNAKE_CASE				,       hypothesis_transform=_SCREAMING_SNAKE_CASE				,       )
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

         return incorrect / total








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCamelCase								=	{
    """configuration_roberta""": ["""ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RobertaConfig""", """RobertaOnnxConfig"""],
    """tokenization_roberta""": ["""RobertaTokenizer"""],
}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	["""RobertaTokenizerFast"""]

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """RobertaForCausalLM""",
         """RobertaForMaskedLM""",
         """RobertaForMultipleChoice""",
         """RobertaForQuestionAnswering""",
         """RobertaForSequenceClassification""",
         """RobertaForTokenClassification""",
         """RobertaModel""",
         """RobertaPreTrainedModel""",
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """TFRobertaForCausalLM""",
         """TFRobertaForMaskedLM""",
         """TFRobertaForMultipleChoice""",
         """TFRobertaForQuestionAnswering""",
         """TFRobertaForSequenceClassification""",
         """TFRobertaForTokenClassification""",
         """TFRobertaMainLayer""",
         """TFRobertaModel""",
         """TFRobertaPreTrainedModel""",
     ]

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """FlaxRobertaForCausalLM""",
         """FlaxRobertaForMaskedLM""",
         """FlaxRobertaForMultipleChoice""",
         """FlaxRobertaForQuestionAnswering""",
         """FlaxRobertaForSequenceClassification""",
         """FlaxRobertaForTokenClassification""",
         """FlaxRobertaModel""",
         """FlaxRobertaPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig
     from .tokenization_roberta import RobertaTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_roberta_fast import RobertaTokenizerFast

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_roberta import (
              ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
              RobertaForCausalLM,
              RobertaForMaskedLM,
              RobertaForMultipleChoice,
              RobertaForQuestionAnswering,
              RobertaForSequenceClassification,
              RobertaForTokenClassification,
              RobertaModel,
              RobertaPreTrainedModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_roberta import (
              TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFRobertaForCausalLM,
              TFRobertaForMaskedLM,
              TFRobertaForMultipleChoice,
              TFRobertaForQuestionAnswering,
              TFRobertaForSequenceClassification,
              TFRobertaForTokenClassification,
              TFRobertaMainLayer,
              TFRobertaModel,
              TFRobertaPreTrainedModel,
          )

     try:
          if not is_flax_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_flax_roberta import (
              FlaxRobertaForCausalLM,
              FlaxRobertaForMaskedLM,
              FlaxRobertaForMultipleChoice,
              FlaxRobertaForQuestionAnswering,
              FlaxRobertaForSequenceClassification,
              FlaxRobertaForTokenClassification,
              FlaxRobertaModel,
              FlaxRobertaPreTrainedModel,
          )

else:
     import sys

     UpperCamelCase								=	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




