



"""simple docstring"""






import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 	__SCREAMING_SNAKE_CASE     (				lowerCAmelCase_		,       unittest.TestCase       ):


					'''simple docstring'''





					_a             =							AudioLDMPipeline
					_a             =							TEXT_TO_AUDIO_PARAMS
					_a             =							TEXT_TO_AUDIO_BATCH_PARAMS
					_a             =							frozenset(
					    [
					        'num_inference_steps',
					        'num_waveforms_per_prompt',
					        'generator',
					        'latents',
					        'output_type',
					        'return_dict',
					        'callback',
					        'callback_steps',
					    ]       )



					def 		snake_case	(	self							:  Any					)-> Optional[Any]:
								torch.manual_seed(0					)
								lowerCamelCase__		:		Any		     =UNetaDConditionModel(
								    block_out_channels=(32, 64),  layers_per_block=2,  sample_size=32,  in_channels=4,  out_channels=4,  down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),  up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),  cross_attention_dim=(32, 64),  class_embed_type='''simple_projection''',  projection_class_embeddings_input_dim=32,  class_embeddings_concat=lowerCamelCase,  )
								lowerCamelCase__		:		List[str]		     =DDIMScheduler(
								    beta_start=0.00_085,  beta_end=0.012,  beta_schedule='''scaled_linear''',  clip_sample=lowerCamelCase,  set_alpha_to_one=lowerCamelCase,  )
								torch.manual_seed(0					)
								lowerCamelCase__		:		int		     =AutoencoderKL(
								    block_out_channels=[32, 64],  in_channels=1,  out_channels=1,  down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],  up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],  latent_channels=4,  )
								torch.manual_seed(0					)
								lowerCamelCase__		:		List[str]		     =ClapTextConfig(
								    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=1000,  projection_dim=32,  )
								lowerCamelCase__		:		Dict		     =ClapTextModelWithProjection(lowerCamelCase					)
								lowerCamelCase__		:		List[Any]		     =RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''',  model_max_length=77					)

								lowerCamelCase__		:		Union[str, Any]		     =SpeechTaHifiGanConfig(
								    model_in_dim=8,  sampling_rate=1_6000,  upsample_initial_channel=16,  upsample_rates=[2, 2],  upsample_kernel_sizes=[4, 4],  resblock_kernel_sizes=[3, 7],  resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]],  normalize_before=lowerCamelCase,  )

								lowerCamelCase__		:		Tuple		     =SpeechTaHifiGan(lowerCamelCase					)

								lowerCamelCase__		:		List[Any]		     ={
								    '''unet''': unet,
								    '''scheduler''': scheduler,
								    '''vae''': vae,
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''vocoder''': vocoder,
								}
								return components



					def 		snake_case	(	self							:  str,  lowerCamelCase							:  Any,  lowerCamelCase							:  List[str]=0					)-> Optional[int]:
								if str(lowerCamelCase					).startswith('''mps'''					):
											lowerCamelCase__		:		Optional[int]		     =torch.manual_seed(lowerCamelCase					)
								else:
											lowerCamelCase__		:		List[Any]		     =torch.Generator(device=lowerCamelCase					).manual_seed(lowerCamelCase					)
								lowerCamelCase__		:		str		     ={
								    '''prompt''': '''A hammer hitting a wooden surface''',
								    '''generator''': generator,
								    '''num_inference_steps''': 2,
								    '''guidance_scale''': 6.0,
								}
								return inputs



					def 		snake_case	(	self							:  int					)-> Union[str, Any]:
								lowerCamelCase__		:		str		     ='''cpu'''  # ensure determinism for the device-dependent torch.Generator

								lowerCamelCase__		:		Union[str, Any]		     =self.get_dummy_components()
								lowerCamelCase__		:		int		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		List[Any]		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		str		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		List[Any]		     =audioldm_pipe(**lowerCamelCase					)
								lowerCamelCase__		:		Any		     =output.audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) == 256

								lowerCamelCase__		:		str		     =audio[:10]
								lowerCamelCase__		:		str		     =np.array(
								    [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033]					)

								assert np.abs(audio_slice - expected_slice					).max() < 1E-2



					def 		snake_case	(	self							:  Dict					)-> List[str]:
								lowerCamelCase__		:		Any		     =self.get_dummy_components()
								lowerCamelCase__		:		int		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		Dict		     =audioldm_pipe.to(lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		int		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		str		     =3 * [inputs['''prompt''']]

								# forward
								lowerCamelCase__		:		Union[str, Any]		     =audioldm_pipe(**lowerCamelCase					)
								lowerCamelCase__		:		Optional[Any]		     =output.audios[0]

								lowerCamelCase__		:		Optional[Any]		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		Tuple		     =3 * [inputs.pop('''prompt'''					)]

								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe.tokenizer(
								    lowerCamelCase,  padding='''max_length''',  max_length=audioldm_pipe.tokenizer.model_max_length,  truncation=lowerCamelCase,  return_tensors='''pt''',  )
								lowerCamelCase__		:		Dict		     =text_inputs['''input_ids'''].to(lowerCamelCase					)

								lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe.text_encoder(
								    lowerCamelCase,  )
								lowerCamelCase__		:		List[Any]		     =prompt_embeds.text_embeds
								# additional L_2 normalization over each hidden-state
								lowerCamelCase__		:		Any		     =F.normalize(lowerCamelCase,  dim=-1					)

								lowerCamelCase__		:		Dict		     =prompt_embeds

								# forward
								lowerCamelCase__		:		int		     =audioldm_pipe(**lowerCamelCase					)
								lowerCamelCase__		:		Tuple		     =output.audios[0]

								assert np.abs(audio_a - audio_a					).max() < 1E-2



					def 		snake_case	(	self							:  Dict					)-> Dict:
								lowerCamelCase__		:		Dict		     =self.get_dummy_components()
								lowerCamelCase__		:		Union[str, Any]		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe.to(lowerCamelCase					)
								lowerCamelCase__		:		Any		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		str		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		int		     =3 * ['''this is a negative prompt''']
								lowerCamelCase__		:		List[Any]		     =negative_prompt
								lowerCamelCase__		:		Tuple		     =3 * [inputs['''prompt''']]

								# forward
								lowerCamelCase__		:		Union[str, Any]		     =audioldm_pipe(**lowerCamelCase					)
								lowerCamelCase__		:		Optional[Any]		     =output.audios[0]

								lowerCamelCase__		:		Optional[Any]		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		Tuple		     =3 * [inputs.pop('''prompt'''					)]

								lowerCamelCase__		:		List[str]		     =[]
								for p in [prompt, negative_prompt]:
											lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe.tokenizer(
											    lowerCamelCase,  padding='''max_length''',  max_length=audioldm_pipe.tokenizer.model_max_length,  truncation=lowerCamelCase,  return_tensors='''pt''',  )
											lowerCamelCase__		:		Optional[int]		     =text_inputs['''input_ids'''].to(lowerCamelCase					)

											lowerCamelCase__		:		Tuple		     =audioldm_pipe.text_encoder(
											    lowerCamelCase,  )
											lowerCamelCase__		:		str		     =text_embeds.text_embeds
											# additional L_2 normalization over each hidden-state
											lowerCamelCase__		:		Any		     =F.normalize(lowerCamelCase,  dim=-1					)

											embeds.append(lowerCamelCase					)

								lowerCamelCase__     ,       lowerCamelCase__		:		Any		     =embeds

								# forward
								lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe(**lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     =output.audios[0]

								assert np.abs(audio_a - audio_a					).max() < 1E-2



					def 		snake_case	(	self							:  int					)-> int:
								lowerCamelCase__		:		List[str]		     ='''cpu'''  # ensure determinism for the device-dependent torch.Generator
								lowerCamelCase__		:		int		     =self.get_dummy_components()
								lowerCamelCase__		:		Optional[int]		     =PNDMScheduler(skip_prk_steps=lowerCamelCase					)
								lowerCamelCase__		:		List[Any]		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		Union[str, Any]		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     ='''egg cracking'''
								lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe(**lowerCamelCase,  negative_prompt=lowerCamelCase					)
								lowerCamelCase__		:		Any		     =output.audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) == 256

								lowerCamelCase__		:		List[Any]		     =audio[:10]
								lowerCamelCase__		:		Dict		     =np.array(
								    [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032]					)

								assert np.abs(audio_slice - expected_slice					).max() < 1E-2



					def 		snake_case	(	self							:  Any					)-> str:
								lowerCamelCase__		:		str		     ='''cpu'''  # ensure determinism for the device-dependent torch.Generator
								lowerCamelCase__		:		str		     =self.get_dummy_components()
								lowerCamelCase__		:		str		     =PNDMScheduler(skip_prk_steps=lowerCamelCase					)
								lowerCamelCase__		:		Dict		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		str		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		List[str]		     ='''A hammer hitting a wooden surface'''

								# test num_waveforms_per_prompt=1 (default)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe(lowerCamelCase,  num_inference_steps=2					).audios

								assert audios.shape == (1, 256)

								# test num_waveforms_per_prompt=1 (default) for batch of prompts
								lowerCamelCase__		:		Dict		     =2
								lowerCamelCase__		:		List[Any]		     =audioldm_pipe([prompt] * batch_size,  num_inference_steps=2					).audios

								assert audios.shape == (batch_size, 256)

								# test num_waveforms_per_prompt for single prompt
								lowerCamelCase__		:		Optional[Any]		     =2
								lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe(lowerCamelCase,  num_inference_steps=2,  num_waveforms_per_prompt=lowerCamelCase					).audios

								assert audios.shape == (num_waveforms_per_prompt, 256)

								# test num_waveforms_per_prompt for batch of prompts
								lowerCamelCase__		:		Any		     =2
								lowerCamelCase__		:		Dict		     =audioldm_pipe(
								    [prompt] * batch_size,  num_inference_steps=2,  num_waveforms_per_prompt=lowerCamelCase					).audios

								assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)



					def 		snake_case	(	self							:  Dict					)-> Any:
								lowerCamelCase__		:		Optional[int]		     ='''cpu'''  # ensure determinism for the device-dependent torch.Generator
								lowerCamelCase__		:		Any		     =self.get_dummy_components()
								lowerCamelCase__		:		Any		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		Tuple		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)
								lowerCamelCase__		:		Any		     =audioldm_pipe.vocoder.config.sampling_rate

								lowerCamelCase__		:		Any		     =self.get_dummy_inputs(lowerCamelCase					)
								lowerCamelCase__		:		Tuple		     =audioldm_pipe(audio_length_in_s=0.016,  **lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     =output.audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) / vocoder_sampling_rate == 0.016

								lowerCamelCase__		:		List[Any]		     =audioldm_pipe(audio_length_in_s=0.032,  **lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     =output.audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) / vocoder_sampling_rate == 0.032



					def 		snake_case	(	self							:  Optional[Any]					)-> List[Any]:
								lowerCamelCase__		:		Tuple		     =self.get_dummy_components()
								lowerCamelCase__		:		Tuple		     =AudioLDMPipeline(**lowerCamelCase					)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		Union[str, Any]		     =['''hey''']

								lowerCamelCase__		:		List[Any]		     =audioldm_pipe(lowerCamelCase,  num_inference_steps=1					)
								lowerCamelCase__		:		Tuple		     =output.audios.shape
								assert audio_shape == (1, 256)

								lowerCamelCase__		:		Tuple		     =audioldm_pipe.vocoder.config
								config.model_in_dim *= 2
								lowerCamelCase__		:		Union[str, Any]		     =SpeechTaHifiGan(lowerCamelCase					).to(lowerCamelCase					)
								lowerCamelCase__		:		Dict		     =audioldm_pipe(lowerCamelCase,  num_inference_steps=1					)
								lowerCamelCase__		:		Any		     =output.audios.shape
								# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
								assert audio_shape == (1, 256)



					def 		snake_case	(	self							:  Optional[Any]					)-> int:
								self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase					)



					def 		snake_case	(	self							:  Tuple					)-> Optional[int]:
								self._test_inference_batch_single_identical(test_mean_pixel_difference=lowerCamelCase					)




					@unittest.skipIf(
					    torch_device != '''cuda''' or not is_xformers_available(),  reason='''XFormers attention is only available with CUDA and `xformers` installed''',  )
					def 		snake_case	(	self							:  Dict					)-> List[Any]:
								self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase					)





@slow
class 	__SCREAMING_SNAKE_CASE     (				unittest.TestCase       ):


					'''simple docstring'''





					def 		snake_case	(	self							:  str					)-> Dict:
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()



					def 		snake_case	(	self							:  List[Any],  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  Optional[Any]="cpu",  lowerCamelCase							:  Optional[Any]=torch.floataa,  lowerCamelCase							:  int=0					)-> str:
								lowerCamelCase__		:		List[str]		     =torch.Generator(device=lowerCamelCase					).manual_seed(lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     =np.random.RandomState(lowerCamelCase					).standard_normal((1, 8, 128, 16)					)
								lowerCamelCase__		:		str		     =torch.from_numpy(lowerCamelCase					).to(device=lowerCamelCase,  dtype=lowerCamelCase					)
								lowerCamelCase__		:		Union[str, Any]		     ={
								    '''prompt''': '''A hammer hitting a wooden surface''',
								    '''latents''': latents,
								    '''generator''': generator,
								    '''num_inference_steps''': 3,
								    '''guidance_scale''': 2.5,
								}
								return inputs



					def 		snake_case	(	self							:  Any					)-> Optional[Any]:
								lowerCamelCase__		:		Tuple		     =AudioLDMPipeline.from_pretrained('''cvssp/audioldm'''					)
								lowerCamelCase__		:		Tuple		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		List[Any]		     =self.get_inputs(lowerCamelCase					)
								lowerCamelCase__		:		int		     =25
								lowerCamelCase__		:		Optional[Any]		     =audioldm_pipe(**lowerCamelCase					).audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) == 8_1920

								lowerCamelCase__		:		int		     =audio[7_7230:7_7240]
								lowerCamelCase__		:		str		     =np.array(
								    [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315]					)
								lowerCamelCase__		:		Tuple		     =np.abs(expected_slice - audio_slice					).max()
								assert max_diff < 1E-2




					def 		snake_case	(	self							:  List[str]					)-> Union[str, Any]:
								lowerCamelCase__		:		Dict		     =AudioLDMPipeline.from_pretrained('''cvssp/audioldm'''					)
								lowerCamelCase__		:		List[Any]		     =LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config					)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe.to(lowerCamelCase					)
								audioldm_pipe.set_progress_bar_config(disable=lowerCamelCase					)

								lowerCamelCase__		:		Tuple		     =self.get_inputs(lowerCamelCase					)
								lowerCamelCase__		:		Optional[int]		     =audioldm_pipe(**lowerCamelCase					).audios[0]

								assert audio.ndim == 1
								assert len(lowerCamelCase					) == 8_1920

								lowerCamelCase__		:		int		     =audio[2_7780:2_7790]
								lowerCamelCase__		:		Tuple		     =np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212]					)
								lowerCamelCase__		:		int		     =np.abs(expected_slice - audio_slice					).max()
								assert max_diff < 3E-2









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


_lowercase			:			List[str]										=						""


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

		class 	__SCREAMING_SNAKE_CASE     (				tr.AbstractTransform       ):


							'''simple docstring'''





							def __init__(	self							:  List[Any],  lowerCamelCase							:  str = " "					)-> List[str]:
										lowerCamelCase__		:		List[str]		     =sentence_delimiter



							def 		snake_case	(	self							:  Any,  lowerCamelCase							:  str					)-> Optional[Any]:
										return list(lowerCamelCase					)




							def 		snake_case	(	self							:  Optional[Any],  lowerCamelCase							:  List[str]					)-> Tuple:
										lowerCamelCase__		:		Optional[int]		     =[]
										for sent_idx, sentence in enumerate(lowerCamelCase					):
													chars.extend(self.process_string(lowerCamelCase					)					)
													if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowerCamelCase					) - 1:
																chars.append(self.sentence_delimiter					)
										return chars





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


_lowercase			:			Dict										=						"\\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"

_lowercase			:			List[Any]										=						"\\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"

_lowercase			:			Dict										=						"\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 	__SCREAMING_SNAKE_CASE     (				datasets.Metric       ):


					'''simple docstring'''





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

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

								return incorrect / total




