

from jiwer import compute_measures

import datasets


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											=     '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (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 words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'

A											=     '\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word 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    >>> wer = datasets.load_metric("wer")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,						_KWARGS_DESCRIPTION							)
class SCREAMING_SNAKE_CASE  (		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',
				    ] ,				)







			def 			__lowerCAmelCase (    self ,				__UpperCamelCase=None ,				__UpperCamelCase=None ,				__UpperCamelCase=False							):

				"""simple docstring"""


				if concatenate_texts:
					return compute_measures(__UpperCamelCase ,				__UpperCamelCase							)["wer"]
				else:
					snake_case_      		= 0
					snake_case_      		= 0
					for prediction, reference in zip(__UpperCamelCase ,				__UpperCamelCase							):
						snake_case_      		= compute_measures(__UpperCamelCase ,				__UpperCamelCase							)
						incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
						total += measures["substitutions"] + measures["deletions"] + measures["hits"]
					return incorrect / total



import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()


class SCREAMING_SNAKE_CASE  (		unittest.TestCase							):






			"""simple docstring"""




			@property
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				torch.manual_seed(0							)
				snake_case_      		= UNetaDModel(
				    block_out_channels=(32, 64) ,				layers_per_block=2 ,				sample_size=32 ,				in_channels=3 ,				out_channels=3 ,				down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,				up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,				)
				return model


			@property
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				torch.manual_seed(0							)
				snake_case_      		= VQModel(
				    block_out_channels=[32, 64] ,				in_channels=3 ,				out_channels=3 ,				down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,				up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,				latent_channels=3 ,				)
				return model


			@property
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				torch.manual_seed(0							)
				snake_case_      		= CLIPTextConfig(
				    bos_token_id=0 ,				eos_token_id=2 ,				hidden_size=32 ,				intermediate_size=37 ,				layer_norm_eps=1E-05 ,				num_attention_heads=4 ,				num_hidden_layers=5 ,				pad_token_id=1 ,				vocab_size=10_00 ,				)
				return CLIPTextModel(__UpperCamelCase							)







			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= self.dummy_uncond_unet
				snake_case_      		= DDIMScheduler()
				snake_case_      		= self.dummy_vq_model

				snake_case_      		= LDMPipeline(unet=__UpperCamelCase ,				vqvae=__UpperCamelCase ,				scheduler=__UpperCamelCase							)
				ldm.to(__UpperCamelCase							)
				ldm.set_progress_bar_config(disable=__UpperCamelCase							)

				snake_case_      		= torch.manual_seed(0							)
				snake_case_      		= ldm(generator=__UpperCamelCase ,				num_inference_steps=2 ,				output_type='numpy'							).images

				snake_case_      		= torch.manual_seed(0							)
				snake_case_      		= ldm(generator=__UpperCamelCase ,				num_inference_steps=2 ,				output_type='numpy' ,				return_dict=__UpperCamelCase							)[0]

				snake_case_      		= image[0, -3:, -3:, -1]
				snake_case_      		= image_from_tuple[0, -3:, -3:, -1]

				assert image.shape == (1, 64, 64, 3)
				snake_case_      		= np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]							)
				snake_case_      		= 1E-2 if torch_device != 'mps' else 3E-2

				assert np.abs(image_slice.flatten() - expected_slice							).max() < tolerance
				assert np.abs(image_from_tuple_slice.flatten() - expected_slice							).max() < tolerance







@slow
@require_torch
class SCREAMING_SNAKE_CASE  (		unittest.TestCase							):






			"""simple docstring"""




			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256'							)
				ldm.to(__UpperCamelCase							)
				ldm.set_progress_bar_config(disable=__UpperCamelCase							)

				snake_case_      		= torch.manual_seed(0							)
				snake_case_      		= ldm(generator=__UpperCamelCase ,				num_inference_steps=5 ,				output_type='numpy'							).images

				snake_case_      		= image[0, -3:, -3:, -1]

				assert image.shape == (1, 2_56, 2_56, 3)
				snake_case_      		= np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447]							)
				snake_case_      		= 1E-2 if torch_device != 'mps' else 3E-2

				assert np.abs(image_slice.flatten() - expected_slice							).max() < tolerance
