






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


lowerCamelCase_       			=   ''''''


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







			class     UpperCamelCase_ (tr.AbstractTransform  ):





				def __init__(   self      :				Union[str, Any]			,			lowerCAmelCase_      :				str = " "		)		->    Union[str, Any]:
							UpperCAmelCase_  :				Union[str, Any]      =      sentence_delimiter





				def   _SCREAMING_SNAKE_CASE   (   self      :				Tuple			,			lowerCAmelCase_      :				str		)		->    Dict:
							return list(lowerCAmelCase_		)





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





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


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_       			=   '''\
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.
'''

lowerCamelCase_       			=   '''
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     UpperCamelCase_ (datasets.Metric  ):





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

				UpperCAmelCase_  :				List[str]      =      0
				UpperCAmelCase_  :				Optional[int]      =      0
				for prediction, reference in zip(lowerCAmelCase_			,			lowerCAmelCase_		):
							UpperCAmelCase_  :				Optional[int]      =      jiwer.compute_measures(
							    lowerCAmelCase_			,			lowerCAmelCase_			,			truth_transform=lowerCAmelCase_			,			hypothesis_transform=lowerCAmelCase_			,			)
							incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
							total += measures["substitutions"] + measures["deletions"] + measures["hits"]

				return incorrect / total











"""simple docstring"""
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


lowerCamelCase_       			=   logging.getLogger()







@unittest.skip('''Temporarily disable the doc tests.'''  )
@require_torch
@require_tf
@slow
class     UpperCamelCase_ (unittest.TestCase  ):





	def   _SCREAMING_SNAKE_CASE   (   self      :				Union[str, Any]			,			lowerCAmelCase_      :				Path			,			lowerCAmelCase_      :				Union[str, None] = None			,			lowerCAmelCase_      :				Union[List[str], None] = None			,			lowerCAmelCase_      :				Union[str, List[str], None] = None			,			lowerCAmelCase_      :				bool = True			,			)		->    Tuple:
				UpperCAmelCase_  :				Optional[Any]      =      [file for file in os.listdir(lowerCAmelCase_		) if os.path.isfile(os.path.join(lowerCAmelCase_			,			lowerCAmelCase_		)		)]

				if identifier is not None:
							UpperCAmelCase_  :				Optional[int]      =      [file for file in files if identifier in file]

				if n_identifier is not None:
							if isinstance(lowerCAmelCase_			,			lowerCAmelCase_		):
										for n_ in n_identifier:
													UpperCAmelCase_  :				List[Any]      =      [file for file in files if n_ not in file]
							else:
										UpperCAmelCase_  :				Optional[Any]      =      [file for file in files if n_identifier not in file]

				UpperCAmelCase_  :				List[Any]      =      ignore_files or []
				ignore_files.append("__init__.py"		)
				UpperCAmelCase_  :				Optional[Any]      =      [file for file in files if file not in ignore_files]

				for file in files:
							# Open all files
							print("Testing"			,			lowerCAmelCase_		)

							if only_modules:
										UpperCAmelCase_  :				str      =      file.split("."		)[0]
										try:
													UpperCAmelCase_  :				Tuple      =      getattr(lowerCAmelCase_			,			lowerCAmelCase_		)
													UpperCAmelCase_  :				int      =      doctest.DocTestSuite(lowerCAmelCase_		)
													UpperCAmelCase_  :				str      =      unittest.TextTestRunner().run(lowerCAmelCase_		)
													self.assertIs(len(result.failures		)			,			0		)
										except AttributeError:
													logger.info(f"""{module_identifier} is not a module."""		)
							else:
										UpperCAmelCase_  :				List[Any]      =      doctest.testfile(str(".." / directory / file		)			,			optionflags=doctest.ELLIPSIS		)
										self.assertIs(result.failed			,			0		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[int]		)		->    List[Any]:
				UpperCAmelCase_  :				Optional[int]      =      Path("src/transformers"		)
				UpperCAmelCase_  :				List[Any]      =      "modeling"
				UpperCAmelCase_  :				Tuple      =      [
				    "modeling_ctrl.py",
				    "modeling_tf_ctrl.py",
				]
				self.analyze_directory(lowerCAmelCase_			,			identifier=lowerCAmelCase_			,			ignore_files=lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Union[str, Any]		)		->    List[Any]:
				UpperCAmelCase_  :				List[str]      =      Path("src/transformers"		)
				UpperCAmelCase_  :				int      =      "tokenization"
				self.analyze_directory(lowerCAmelCase_			,			identifier=lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Optional[Any]		)		->    Optional[Any]:
				UpperCAmelCase_  :				int      =      Path("src/transformers"		)
				UpperCAmelCase_  :				Any      =      "configuration"
				self.analyze_directory(lowerCAmelCase_			,			identifier=lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				Any		)		->    Any:
				UpperCAmelCase_  :				int      =      Path("src/transformers"		)
				UpperCAmelCase_  :				List[Any]      =      ["configuration", "modeling", "tokenization"]
				self.analyze_directory(lowerCAmelCase_			,			n_identifier=lowerCAmelCase_		)





	def   _SCREAMING_SNAKE_CASE   (   self      :				List[str]		)		->    Dict:
				UpperCAmelCase_  :				List[str]      =      Path("docs/source"		)
				UpperCAmelCase_  :				int      =      ["favicon.ico"]
				self.analyze_directory(lowerCAmelCase_			,			ignore_files=lowerCAmelCase_			,			only_modules=lowerCAmelCase_		)



