'''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    :     int         =       ''''''


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







   class lowercase_       (		tr.AbstractTransform			):







      """simple docstring"""

      def __init__(      self      :			Tuple, UpperCamelCase__      :			str = " "     )  ->			str:
           _A    		=  sentence_delimiter
      def 	__UpperCAmelCase   (      self      :			Optional[Any], UpperCamelCase__      :			str     )  ->			List[str]:
           return list(UpperCamelCase__     )

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






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


_UpperCAmelCase    :     Tuple         =       '''\
@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    :     Dict         =       '''\
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    :     List[Any]         =       '''
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 lowercase_       (		datasets.Metric			):







   """simple docstring"""

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

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

        return incorrect / total






import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


A_			:					Any    			=     logging.get_logger(__name__)



class        _a		:


					'''simple docstring'''






					UpperCAmelCase__:  str    				=			None



@experimental
def 		UpperCamelCase   (lowercase_:					int       , lowercase_:					Any       , lowercase_:					str       , lowercase_:					str       , lowercase_:					List[str]       , lowercase_:					List[Any]       , lowercase_:					Union[str, Any]   )	-> Union[str, Any]:
	if ParallelBackendConfig.backend_name is None:
		return _map_with_multiprocessing_pool(
		    lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_   )

	return _map_with_joblib(lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_       , lowercase_   )

def 		UpperCamelCase   (lowercase_:					Tuple       , lowercase_:					List[Any]       , lowercase_:					Tuple       , lowercase_:					Tuple       , lowercase_:					List[str]       , lowercase_:					Dict       , lowercase_:					Tuple   )	-> Tuple:
	A__				:       Union[str, Any]	  =						num_proc if num_proc <= len(lowercase_   ) else len(lowercase_   )
	A__				:       str	  =						[]  # We organize the splits ourselve (contiguous splits)
	for index in range(lowercase_   ):
		A__				:       Tuple	  =						len(lowercase_   ) // num_proc
		A__				:       Tuple	  =						len(lowercase_   ) % num_proc
		A__				:       Optional[Any]	  =						div * index + min(lowercase_       , lowercase_   )
		A__				:       Union[str, Any]	  =						start + div + (1 if index < mod else 0)
		split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)   )

	if len(lowercase_   ) != sum(len(i[1]   ) for i in split_kwds   ):
		raise ValueError(
		    f"""Error dividing inputs iterable among processes. """
		    f"""Total number of objects {len(lowercase_   )}, """
		    f"""length: {sum(len(i[1]   ) for i in split_kwds   )}"""   )

	logger.info(
	    f"""Spawning {num_proc} processes for {len(lowercase_   )} objects in slices of {[len(i[1]   ) for i in split_kwds]}"""   )
	A__  ,  A__				:       Optional[int]	  =						None, None
	if not disable_tqdm:
		A__  ,  A__				:       List[str]	  =						(RLock(),), tqdm.set_lock
	with Pool(lowercase_       , initargs=lowercase_       , initializer=lowercase_   ) as pool:
		A__				:       Optional[Any]	  =						pool.map(lowercase_       , lowercase_   )
	logger.info(f"""Finished {num_proc} processes"""   )
	A__				:       Tuple	  =						[obj for proc_res in mapped for obj in proc_res]
	logger.info(f"""Unpacked {len(lowercase_   )} objects"""   )

	return mapped

def 		UpperCamelCase   (lowercase_:					Union[str, Any]       , lowercase_:					Dict       , lowercase_:					str       , lowercase_:					Union[str, Any]       , lowercase_:					List[Any]       , lowercase_:					Dict       , lowercase_:					Optional[Any]   )	-> Union[str, Any]:
	# progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
	# and it requires monkey-patching joblib internal classes which is subject to change
	import joblib

	with joblib.parallel_backend(ParallelBackendConfig.backend_name       , n_jobs=lowercase_   ):
		return joblib.Parallel()(
		    joblib.delayed(lowercase_   )((function, obj, types, None, True, None)   ) for obj in iterable   )


@experimental
@contextlib.contextmanager
def 		UpperCamelCase   (lowercase_:					str   )	-> str:
	A__				:       int	  =						backend_name

	if backend_name == "spark":
		from joblibspark import register_spark

		register_spark()

		# TODO: call create_cache_and_write_probe if "download" in steps
		# TODO: raise NotImplementedError when Dataset.map etc is called

	try:
		yield
	finally:
		A__				:       Optional[Any]	  =						None



