"""simple docstring"""





import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class 			_snake_case		(     __snake_case ,							__snake_case ,							__snake_case ,							unittest.TestCase			):







				"""simple docstring"""






				a      =    AltDiffusionPipeline
				a      =    TEXT_TO_IMAGE_PARAMS
				a      =    TEXT_TO_IMAGE_BATCH_PARAMS
				a      =    TEXT_TO_IMAGE_IMAGE_PARAMS
				a      =    TEXT_TO_IMAGE_IMAGE_PARAMS





				def 		_lowerCAmelCase		(   self				:				Dict):



											"""simple docstring"""







											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     UNetaDConditionModel(
											    block_out_channels=(3_2, 6_4)   ,     layers_per_block=2   ,     sample_size=3_2   ,     in_channels=4   ,     out_channels=4   ,     down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")   ,     up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")   ,     cross_attention_dim=3_2   ,     )
											_SCREAMING_SNAKE_CASE		:    Any      	=     DDIMScheduler(
											    beta_start=0.00_085   ,     beta_end=0.012   ,     beta_schedule="""scaled_linear"""   ,     clip_sample=_A   ,     set_alpha_to_one=_A   ,     )
											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    Dict      	=     AutoencoderKL(
											    block_out_channels=[3_2, 6_4]   ,     in_channels=3   ,     out_channels=3   ,     down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]   ,     up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]   ,     latent_channels=4   ,     )

											# TODO: address the non-deterministic text encoder (fails for save-load tests)
											# torch.manual_seed(0)
											# text_encoder_config = RobertaSeriesConfig(
											#     hidden_size=32,
											#     project_dim=32,
											#     intermediate_size=37,
											#     layer_norm_eps=1e-05,
											#     num_attention_heads=4,
											#     num_hidden_layers=5,
											#     vocab_size=5002,
											# )
											# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    List[str]      	=     CLIPTextConfig(
											    bos_token_id=0   ,     eos_token_id=2   ,     hidden_size=3_2   ,     projection_dim=3_2   ,     intermediate_size=3_7   ,     layer_norm_eps=1e-05   ,     num_attention_heads=4   ,     num_hidden_layers=5   ,     pad_token_id=1   ,     vocab_size=5_0_0_2   ,     )
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     CLIPTextModel(_A)

											_SCREAMING_SNAKE_CASE		:    str      	=     XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""")
											_SCREAMING_SNAKE_CASE		:    str      	=     7_7

											_SCREAMING_SNAKE_CASE		:    Optional[int]      	=     {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vae""": vae,
											    """text_encoder""": text_encoder,
											    """tokenizer""": tokenizer,
											    """safety_checker""": None,
											    """feature_extractor""": None,
											}
											return components





				def 		_lowerCAmelCase		(   self				:				List[str]   ,     _A				:				Optional[int]   ,     _A				:				Tuple=0):



											"""simple docstring"""







											if str(_A).startswith("""mps"""):
																		_SCREAMING_SNAKE_CASE		:    List[str]      	=     torch.manual_seed(_A)
											else:
																		_SCREAMING_SNAKE_CASE		:    str      	=     torch.Generator(device=_A).manual_seed(_A)
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs





				def 		_lowerCAmelCase		(   self				:				str):



											"""simple docstring"""







											super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)





				def 		_lowerCAmelCase		(   self				:				Any):



											"""simple docstring"""







											super().test_inference_batch_single_identical(expected_max_diff=3e-3)





				def 		_lowerCAmelCase		(   self				:				Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Any      	=     """cpu"""  # ensure determinism for the device-dependent torch.Generator

											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     self.get_dummy_components()
											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    List[str]      	=     RobertaSeriesConfig(
											    hidden_size=3_2   ,     project_dim=3_2   ,     intermediate_size=3_7   ,     layer_norm_eps=1e-05   ,     num_attention_heads=4   ,     num_hidden_layers=5   ,     vocab_size=5_0_0_2   ,     )
											# TODO: remove after fixing the non-deterministic text encoder
											_SCREAMING_SNAKE_CASE		:    Optional[int]      	=     RobertaSeriesModelWithTransformation(_A)
											_SCREAMING_SNAKE_CASE		:    str      	=     text_encoder

											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     AltDiffusionPipeline(**_A)
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     alt_pipe.to(_A)
											alt_pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     self.get_dummy_inputs(_A)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     """A photo of an astronaut"""
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     alt_pipe(**_A)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     output.images
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     image[0, -3:, -3:, -1]

											assert image.shape == (1, 6_4, 6_4, 3)
											_SCREAMING_SNAKE_CASE		:    str      	=     np.array(
											    [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093])

											assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2





				def 		_lowerCAmelCase		(   self				:				int):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     """cpu"""  # ensure determinism for the device-dependent torch.Generator

											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     self.get_dummy_components()
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     PNDMScheduler(skip_prk_steps=_A)
											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     RobertaSeriesConfig(
											    hidden_size=3_2   ,     project_dim=3_2   ,     intermediate_size=3_7   ,     layer_norm_eps=1e-05   ,     num_attention_heads=4   ,     num_hidden_layers=5   ,     vocab_size=5_0_0_2   ,     )
											# TODO: remove after fixing the non-deterministic text encoder
											_SCREAMING_SNAKE_CASE		:    Optional[int]      	=     RobertaSeriesModelWithTransformation(_A)
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     text_encoder
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     AltDiffusionPipeline(**_A)
											_SCREAMING_SNAKE_CASE		:    Dict      	=     alt_pipe.to(_A)
											alt_pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     self.get_dummy_inputs(_A)
											_SCREAMING_SNAKE_CASE		:    Any      	=     alt_pipe(**_A)
											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     output.images
											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     image[0, -3:, -3:, -1]

											assert image.shape == (1, 6_4, 6_4, 3)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     np.array(
											    [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237])

											assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2




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







				"""simple docstring"""






				def 		_lowerCAmelCase		(   self				:				Dict):



											"""simple docstring"""







											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()





				def 		_lowerCAmelCase		(   self				:				List[str]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    int      	=     AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion"""   ,     safety_checker=_A)
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     alt_pipe.to(_A)
											alt_pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     """A painting of a squirrel eating a burger"""
											_SCREAMING_SNAKE_CASE		:    List[str]      	=     torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     alt_pipe([prompt]   ,     generator=_A   ,     guidance_scale=6.0   ,     num_inference_steps=2_0   ,     output_type="""np""")

											_SCREAMING_SNAKE_CASE		:    Tuple      	=     output.images

											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586])

											assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2





				def 		_lowerCAmelCase		(   self				:				Dict):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Dict      	=     DDIMScheduler.from_pretrained("""BAAI/AltDiffusion"""   ,     subfolder="""scheduler""")

											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion"""   ,     scheduler=_A   ,     safety_checker=_A)
											_SCREAMING_SNAKE_CASE		:    Optional[int]      	=     alt_pipe.to(_A)
											alt_pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:    List[str]      	=     """A painting of a squirrel eating a burger"""
											_SCREAMING_SNAKE_CASE		:    Dict      	=     torch.manual_seed(0)

											_SCREAMING_SNAKE_CASE		:    Any      	=     alt_pipe([prompt]   ,     generator=_A   ,     num_inference_steps=2   ,     output_type="""numpy""")
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     output.images

											_SCREAMING_SNAKE_CASE		:    Dict      	=     image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											_SCREAMING_SNAKE_CASE		:    List[str]      	=     np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323])

											assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2




"""simple docstring"""


from jiwer import compute_measures

import datasets


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_    							=					"""\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The 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.

This 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.

Word error rate can then be computed as:

WER = (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 words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
"""

A_    							=					"""
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> wer = datasets.load_metric(\"wer\")
    >>> wer_score = wer.compute(predictions=predictions, references=references)
    >>> print(wer_score)
    0.5
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,	_KWARGS_DESCRIPTION			)
class  __lowerCamelCase  ( datasets.Metric			):




				def        UpperCAmelCase__						(				self   ):
							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        UpperCAmelCase__						(				self							,						UpperCAmelCase=None							,						UpperCAmelCase=None							,						UpperCAmelCase=False   ):
							if concatenate_texts:
										return compute_measures(UpperCAmelCase							,						UpperCAmelCase   )["wer"]
							else:
										lowerCamelCase_					=  0
										lowerCamelCase_					=  0
										for prediction, reference in zip(UpperCAmelCase							,						UpperCAmelCase   ):
													lowerCamelCase_					=  compute_measures(UpperCAmelCase							,						UpperCAmelCase   )
													incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
													total += measures["substitutions"] + measures["deletions"] + measures["hits"]
										return incorrect / total



