





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


a_ =			""


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






       class 		__snake_case					(		tr.AbstractTransform     ):





        """simple docstring"""


        def __init__(    self					,						__lowerCamelCase = " "  ):



            '''simple docstring'''




            __A    :						str						 =     sentence_delimiter

        def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



            '''simple docstring'''




            return list(__lowercase  )







        def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



            '''simple docstring'''




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






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


a_ =			"\\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_ =			"\\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_ =			"\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 		__snake_case					(		datasets.Metric     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''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 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=False  ):



     '''simple docstring'''




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

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

     return incorrect / total










from timeit import timeit

lowercase__				:     Union[str, Any] 		=						{
    "MALAYALAM": True,
    "String": False,
    "rotor": True,
    "level": True,
    "A": True,
    "BB": True,
    "ABC": False,
    "amanaplanacanalpanama": True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     0
	snake_case_		    =     len(_A							) - 1
	while start_i < end_i:
		if s[start_i] == s[end_i]:
			start_i += 1
			end_i -= 1
		else:
			return False
	return True


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     len(_A							) // 2
	snake_case_		    =     len(_A							)

	# We need to traverse till half of the length of string
	# as we can get access of the i'th last element from
	# i'th index.
	# eg: [0,1,2,3,4,5] => 4th index can be accessed
	# with the help of 1st index (i==n-i-1)
	# where n is length of string
	return all(s[i] == s[n - i - 1] for i in range(_A							)							)


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	if len(_A							) <= 2:
		return True
	if s[0] == s[len(_A							) - 1]:
		return is_palindrome_recursive(s[1:-1]							)
	else:
		return False


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	return s == s[::-1]


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     f"all({name}(key) is value for key, value in test_data.items())"
	snake_case_		    =     f"from __main__ import test_data, {name}"
	snake_case_		    =     500000
	snake_case_		    =     timeit(stmt=_A     ,	setup=_A     ,	number=_A							)
	print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds"							)


if __name__ == "__main__":
		for key, value in test_data.items():
				assert is_palindrome(key) is is_palindrome_recursive(key)
				assert is_palindrome(key) is is_palindrome_slice(key)
				print(f'''{key:21} {value}''')
		print("a man a plan a canal panama")

		# finished 500,000 runs in 0.46793 seconds
		benchmark_function("is_palindrome_slice")
		# finished 500,000 runs in 0.85234 seconds
		benchmark_function("is_palindrome")
		# finished 500,000 runs in 1.32028 seconds
		benchmark_function("is_palindrome_recursive")
		# finished 500,000 runs in 2.08679 seconds
		benchmark_function("is_palindrome_traversal")
