"""simple docstring"""





import os
import sys
import unittest


__A  =				os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__A  =				os.path.join(git_repo_path, '''src''', '''diffusers''')
class  _snake_case     (					unittest.TestCase		):






						def       lowerCamelCase__     (       self      :			Optional[Any]    ):
													__lowerCamelCase					:		Optional[int]		   =     find_backend("    if not is_torch_available():"    )
													self.assertEqual(UpperCAmelCase							,					"torch"    )

													# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
													# self.assertEqual(backend_with_underscore, "tensorflow_text")

													__lowerCamelCase					:		str		   =     find_backend("    if not (is_torch_available() and is_transformers_available()):"    )
													self.assertEqual(UpperCAmelCase							,					"torch_and_transformers"    )

													# double_backend_with_underscore = find_backend(
													#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
													# )
													# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

													__lowerCamelCase					:		Tuple		   =     find_backend(
													    "    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):"    )
													self.assertEqual(UpperCAmelCase							,					"torch_and_transformers_and_onnx"    )






						def       lowerCamelCase__     (       self      :			Dict    ):
													__lowerCamelCase					:		Optional[Any]		   =     read_init()
													# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
													self.assertIn("torch"							,					UpperCAmelCase    )
													self.assertIn("torch_and_transformers"							,					UpperCAmelCase    )
													self.assertIn("flax_and_transformers"							,					UpperCAmelCase    )
													self.assertIn("torch_and_transformers_and_onnx"							,					UpperCAmelCase    )

													# Likewise, we can't assert on the exact content of a key
													self.assertIn("UNet2DModel"							,					objects["torch"]    )
													self.assertIn("FlaxUNet2DConditionModel"							,					objects["flax"]    )
													self.assertIn("StableDiffusionPipeline"							,					objects["torch_and_transformers"]    )
													self.assertIn("FlaxStableDiffusionPipeline"							,					objects["flax_and_transformers"]    )
													self.assertIn("LMSDiscreteScheduler"							,					objects["torch_and_scipy"]    )
													self.assertIn("OnnxStableDiffusionPipeline"							,					objects["torch_and_transformers_and_onnx"]    )






						def       lowerCamelCase__     (       self      :			Any    ):
													__lowerCamelCase					:		Union[str, Any]		   =     create_dummy_object("CONSTANT"							,					"'torch'"    )
													self.assertEqual(UpperCAmelCase							,					"\nCONSTANT = None\n"    )

													__lowerCamelCase					:		Optional[Any]		   =     create_dummy_object("function"							,					"'torch'"    )
													self.assertEqual(
													    UpperCAmelCase							,					"\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"    )

													__lowerCamelCase					:		List[str]		   =     "\nclass FakeClass(metaclass=DummyObject):\n    _backends = 'torch'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, 'torch')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n"
													__lowerCamelCase					:		Optional[int]		   =     create_dummy_object("FakeClass"							,					"'torch'"    )
													self.assertEqual(UpperCAmelCase							,					UpperCAmelCase    )







						def       lowerCamelCase__     (       self      :			List[Any]    ):
													__lowerCamelCase					:		str		   =     "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n"
													__lowerCamelCase					:		Union[str, Any]		   =     create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]}    )
													self.assertEqual(dummy_files["torch"]							,					UpperCAmelCase    )
"""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		):






										def __init__(       self      :			Optional[Any]							,					UpperCAmelCase      :			str = " "    ):
																	__lowerCamelCase					:		List[str]		   =     sentence_delimiter






										def       lowerCamelCase__     (       self      :			Tuple							,					UpperCAmelCase      :			str    ):
																	return list(UpperCAmelCase    )







										def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			List[str]    ):
																	__lowerCamelCase					:		Any		   =     []
																	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

				__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  =				'''\
@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.}
}
'''

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

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






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

													__lowerCamelCase					:		Optional[int]		   =     0
													__lowerCamelCase					:		Optional[int]		   =     0
													for prediction, reference in zip(UpperCAmelCase							,					UpperCAmelCase    ):
																				__lowerCamelCase					:		Dict		   =     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