

"""simple docstring"""




import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar







class      __lowercase			(    unittest.TestCase					):

  def    __lowercase       (  self		:			Optional[Any]    ):






   '''simple docstring'''
   UpperCAmelCase__					:  int					   =					logging.get_logger()

   # the current default level is logging.WARNING
   UpperCAmelCase__					:  Tuple					   =					logging.get_verbosity()

   logging.set_verbosity_error()
   self.assertEqual(logger.getEffectiveLevel()					,logging.get_verbosity()    )

   logging.set_verbosity_warning()
   self.assertEqual(logger.getEffectiveLevel()					,logging.get_verbosity()    )

   logging.set_verbosity_info()
   self.assertEqual(logger.getEffectiveLevel()					,logging.get_verbosity()    )

   logging.set_verbosity_debug()
   self.assertEqual(logger.getEffectiveLevel()					,logging.get_verbosity()    )

   # restore to the original level
   logging.set_verbosity(A    )

  def    __lowercase       (  self		:			List[Any]    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Optional[Any]					   =					logging.get_verbosity()

   UpperCAmelCase__					:  int					   =					logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
   UpperCAmelCase__					:  int					   =					"""Testing 1, 2, 3"""

   # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
   if level_origin <= logging.WARNING:
    with CaptureLogger(A    ) as cl:
     logger.warning(A    )
    self.assertEqual(cl.out					,msg + """\n"""    )

   # this is setting the level for all of `transformers.*` loggers
   logging.set_verbosity_error()

   # should not be able to log warnings
   with CaptureLogger(A    ) as cl:
    logger.warning(A    )
   self.assertEqual(cl.out					,""""""    )

   # should be able to log warnings again
   logging.set_verbosity_warning()
   with CaptureLogger(A    ) as cl:
    logger.warning(A    )
   self.assertEqual(cl.out					,msg + """\n"""    )

   # restore to the original level
   logging.set_verbosity(A    )

  @mockenv(TRANSFORMERS_VERBOSITY="""error"""    )
  def    __lowercase       (  self		:			str    ):






   '''simple docstring'''
   # reset for the env var to take effect, next time some logger call is made
   transformers.utils.logging._reset_library_root_logger()
   # this action activates the env var
   UpperCAmelCase__					:  Any					   =					logging.get_logger("""transformers.models.bart.tokenization_bart"""    )

   UpperCAmelCase__					:  Optional[Any]					   =					os.getenv("""TRANSFORMERS_VERBOSITY"""					,A    )
   UpperCAmelCase__					:  Optional[int]					   =					logging.log_levels[env_level_str]

   UpperCAmelCase__					:  str					   =					logging.get_verbosity()
   self.assertEqual(
       A					,A					,f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}"					,)

   # restore to the original level
   UpperCAmelCase__					:  Any					   =					""""""
   transformers.utils.logging._reset_library_root_logger()

  @mockenv(TRANSFORMERS_VERBOSITY="""super-error"""    )
  def    __lowercase       (  self		:			str    ):






   '''simple docstring'''
   # reset for the env var to take effect, next time some logger call is made
   transformers.utils.logging._reset_library_root_logger()
   UpperCAmelCase__					:  Dict					   =					logging.logging.getLogger()
   with CaptureLogger(A    ) as cl:
    # this action activates the env var
    logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
   self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error"""					,cl.out    )

   # no need to restore as nothing was changed




  def    __lowercase       (  self		:			Optional[Any]    ):






   '''simple docstring'''
   # testing `logger.warning_advice()`
   transformers.utils.logging._reset_library_root_logger()

   UpperCAmelCase__					:  List[Any]					   =					logging.get_logger("""transformers.models.bart.tokenization_bart"""    )
   UpperCAmelCase__					:  List[Any]					   =					"""Testing 1, 2, 3"""

   with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1"""    ):
    # nothing should be logged as env var disables this method
    with CaptureLogger(A    ) as cl:
     logger.warning_advice(A    )
    self.assertEqual(cl.out					,""""""    )

   with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""""""    ):
    # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
    with CaptureLogger(A    ) as cl:
     logger.warning_advice(A    )
    self.assertEqual(cl.out					,msg + """\n"""    )







def   lowerCAmelCase						(					):
 '''simple docstring'''





 disable_progress_bar()
 assert are_progress_bars_disabled()

 enable_progress_bar()
 assert not are_progress_bars_disabled()








"""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


__UpperCAmelCase =				''


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







      class      __lowercase			(    tr.AbstractTransform					):

        def __init__(  self		:			List[str]					,A		:			str = " "    ):






         '''simple docstring'''
         UpperCAmelCase__					:  str					   =					sentence_delimiter

        def    __lowercase       (  self		:			Union[str, Any]					,A		:			str    ):






         '''simple docstring'''
         return list(A    )




        def    __lowercase       (  self		:			int					,A		:			List[str]    ):






         '''simple docstring'''
         UpperCAmelCase__					:  Any					   =					[]
         for sent_idx, sentence in enumerate(A    ):
          chars.extend(self.process_string(A    )    )
          if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A    ) - 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 =				'\\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'

__UpperCAmelCase =				'\\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'

__UpperCAmelCase =				'\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      __lowercase			(    datasets.Metric					):

  def    __lowercase       (  self		:			int    ):






   '''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    __lowercase       (  self		:			Union[str, Any]					,A		:			Optional[Any]					,A		:			Tuple					,A		:			str=False    ):






   '''simple docstring'''
   if concatenate_texts:
    return jiwer.compute_measures(
        A					,A					,truth_transform=A					,hypothesis_transform=A					,)["wer"]

   UpperCAmelCase__					:  Tuple					   =					0
   UpperCAmelCase__					:  Any					   =					0
   for prediction, reference in zip(A					,A    ):
    UpperCAmelCase__					:  List[str]					   =					jiwer.compute_measures(
        A					,A					,truth_transform=A					,hypothesis_transform=A					,)
    incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
    total += measures["substitutions"] + measures["deletions"] + measures["hits"]

   return incorrect / total





