




"""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				:     Tuple					=				""""""


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






					class        __magic_name__				(			tr.AbstractTransform							):






									'''simple docstring'''





									def __init__(			self						,					_a = " "					):





												"""simple docstring"""
												lowerCamelCase      =   sentence_delimiter





									def   _lowerCAmelCase							(			self						,					_a					):





												"""simple docstring"""
												return list(_a					)





									def   _lowerCAmelCase							(			self						,					_a					):





												"""simple docstring"""
												lowerCamelCase      =   []
												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




					lowerCAmelCase				:     List[str]					=				tr.Compose(
					    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
					)
else:
					lowerCAmelCase				:     Tuple					=				tr.Compose(
					    [
					        tr.RemoveMultipleSpaces(),
					        tr.Strip(),
					        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
					        tr.ReduceToListOfListOfChars(),
					    ]
					)


lowerCAmelCase				:     Any					=				"""\
@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				:     Union[str, Any]					=				"""\
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				:     Dict					=				"""
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        __magic_name__				(			datasets.Metric							):






				'''simple docstring'''





				def   _lowerCAmelCase							(			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   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a=False					):





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

							lowerCamelCase      =   0
							lowerCamelCase      =   0
							for prediction, reference in zip(_a						,					_a					):
										lowerCamelCase      =   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









"""simple docstring"""




import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class        __magic_name__				(			UpperCAmelCase__		,   unittest.TestCase							):






				'''simple docstring'''
				__UpperCamelCase         =		DiTPipeline
				__UpperCamelCase         =		CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
				__UpperCamelCase         =		PipelineTesterMixin.required_optional_params - {
				    "latents",
				    "num_images_per_prompt",
				    "callback",
				    "callback_steps",
				}
				__UpperCamelCase         =		CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
				__UpperCamelCase         =		False





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							torch.manual_seed(0					)
							lowerCamelCase      =   TransformeraDModel(
							    sample_size=16						,					num_layers=2						,					patch_size=4						,					attention_head_dim=8						,					num_attention_heads=2						,					in_channels=4						,					out_channels=8						,					attention_bias=_a						,					activation_fn="""gelu-approximate"""						,					num_embeds_ada_norm=1_000						,					norm_type="""ada_norm_zero"""						,					norm_elementwise_affine=_a						,					)
							lowerCamelCase      =   AutoencoderKL()
							lowerCamelCase      =   DDIMScheduler()
							lowerCamelCase      =   {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
							return components





				def   _lowerCAmelCase							(			self						,					_a						,					_a=0					):





							"""simple docstring"""
							if str(_a					).startswith("""mps"""					):
										lowerCamelCase      =   torch.manual_seed(_a					)
							else:
										lowerCamelCase      =   torch.Generator(device=_a					).manual_seed(_a					)
							lowerCamelCase      =   {
							    """class_labels""": [1],
							    """generator""": generator,
							    """num_inference_steps""": 2,
							    """output_type""": """numpy""",
							}
							return inputs





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   """cpu"""

							lowerCamelCase      =   self.get_dummy_components()
							lowerCamelCase      =   self.pipeline_class(**_a					)
							pipe.to(_a					)
							pipe.set_progress_bar_config(disable=_a					)

							lowerCamelCase      =   self.get_dummy_inputs(_a					)
							lowerCamelCase      =   pipe(**_a					).images
							lowerCamelCase      =   image[0, -3:, -3:, -1]

							self.assertEqual(image.shape						,					(1, 16, 16, 3)					)
							lowerCamelCase      =   np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457]					)
							lowerCamelCase      =   np.abs(image_slice.flatten() - expected_slice					).max()
							self.assertLessEqual(_a						,					1e-3					)





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							self._test_inference_batch_single_identical(relax_max_difference=_a						,					expected_max_diff=1e-3					)





				@unittest.skipIf(
				    torch_device != """cuda""" or not is_xformers_available()						,					reason="""XFormers attention is only available with CUDA and `xformers` installed"""						,					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3					)






@require_torch_gpu
@slow
class        __magic_name__				(			unittest.TestCase							):






				'''simple docstring'''





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   torch.manual_seed(0					)

							lowerCamelCase      =   DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256"""					)
							pipe.to("""cuda"""					)

							lowerCamelCase      =   ["""vase""", """umbrella""", """white shark""", """white wolf"""]
							lowerCamelCase      =   pipe.get_label_ids(_a					)

							lowerCamelCase      =   pipe(_a						,					generator=_a						,					num_inference_steps=40						,					output_type="""np"""					).images

							for word, image in zip(_a						,					_a					):
										lowerCamelCase      =   load_numpy(
										    f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy'					)
										assert np.abs((expected_image - image).max()					) < 1e-2





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512"""					)
							lowerCamelCase      =   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config					)
							pipe.to("""cuda"""					)

							lowerCamelCase      =   ["""vase""", """umbrella"""]
							lowerCamelCase      =   pipe.get_label_ids(_a					)

							lowerCamelCase      =   torch.manual_seed(0					)
							lowerCamelCase      =   pipe(_a						,					generator=_a						,					num_inference_steps=25						,					output_type="""np"""					).images

							for word, image in zip(_a						,					_a					):
										lowerCamelCase      =   load_numpy(
										    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
										    f'/dit/{word}_512.npy'					)

										assert np.abs((expected_image - image).max()					) < 1e-1



