
"""simple docstring"""




import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


class 			__magic_name__       (       unittest.TestCase ):
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
       @property
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			List[str]       =     1
         _lowercase:			Optional[int]       =     3
         _lowercase:			Optional[int]       =     (32, 32)

         _lowercase:			Any       =     floats_tensor((batch_size, num_channels) + sizes ,				rng=random.Random(0       )       ).to(A_       )
         return image
       @property
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         torch.manual_seed(0       )
         _lowercase:			Optional[int]       =     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 ,				)
         return model
       @property
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         torch.manual_seed(0       )
         _lowercase:			Any       =     AutoencoderKL(
             block_out_channels=[32, 64] ,				in_channels=3 ,				out_channels=3 ,				down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,				up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,				latent_channels=4 ,				)
         return model
       @property
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         torch.manual_seed(0       )
         _lowercase:			Optional[Any]       =     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=1000 ,				)
         return CLIPTextModel(A_       )
       @property
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         def extract(*A_ ,				**A_       ):


           class 			__magic_name__       :
                  def __init__(     self       )     ->	str:





                    """simple docstring"""




                    _lowercase:			List[Any]       =     torch.ones([0]       )



                  def 							lowercase_							(     self ,				A_       )     ->	Tuple:





                    """simple docstring"""




                    self.pixel_values.to(A_       )
                    return self

           return Out()

         return extract
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			str       =     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
         _lowercase:			int       =     self.dummy_cond_unet
         _lowercase:			Tuple       =     DDIMScheduler(
             beta_start=0.0_00_85 ,				beta_end=0.0_12 ,				beta_schedule='''scaled_linear''' ,				clip_sample=A_ ,				set_alpha_to_one=A_ ,				)

         _lowercase:			str       =     self.dummy_vae
         _lowercase:			Optional[int]       =     self.dummy_text_encoder
         _lowercase:			Dict       =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

         # make sure here that pndm scheduler skips prk
         _lowercase:			Tuple       =     StableDiffusionPipeline(
             unet=A_ ,				scheduler=A_ ,				vae=A_ ,				text_encoder=A_ ,				tokenizer=A_ ,				safety_checker=A_ ,				feature_extractor=self.dummy_extractor ,				)
         _lowercase:			Optional[int]       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			Tuple       =     '''A painting of a squirrel eating a burger'''

         _lowercase:			Dict       =     torch.Generator(device=A_       ).manual_seed(0       )
         _lowercase:			Any       =     sd_pipe([prompt] ,				generator=A_ ,				guidance_scale=6.0 ,				num_inference_steps=2 ,				output_type='''np'''       )
         _lowercase:			Optional[Any]       =     output.images

         _lowercase:			str       =     torch.Generator(device=A_       ).manual_seed(0       )
         _lowercase:			Union[str, Any]       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=6.0 ,				num_inference_steps=2 ,				output_type='''np''' ,				return_dict=A_ ,				)[0]

         _lowercase:			List[Any]       =     image[0, -3:, -3:, -1]
         _lowercase:			Tuple       =     image_from_tuple[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         _lowercase:			Optional[Any]       =     np.array([0.57_56, 0.61_18, 0.50_05, 0.50_41, 0.54_71, 0.47_26, 0.49_76, 0.48_65, 0.48_64]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 1E-2
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
         _lowercase:			str       =     self.dummy_cond_unet
         _lowercase:			int       =     PNDMScheduler(skip_prk_steps=A_       )
         _lowercase:			List[str]       =     self.dummy_vae
         _lowercase:			str       =     self.dummy_text_encoder
         _lowercase:			Optional[int]       =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

         # make sure here that pndm scheduler skips prk
         _lowercase:			Dict       =     StableDiffusionPipeline(
             unet=A_ ,				scheduler=A_ ,				vae=A_ ,				text_encoder=A_ ,				tokenizer=A_ ,				safety_checker=A_ ,				feature_extractor=self.dummy_extractor ,				)
         _lowercase:			Tuple       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			Any       =     '''A painting of a squirrel eating a burger'''
         _lowercase:			List[str]       =     torch.Generator(device=A_       ).manual_seed(0       )
         _lowercase:			Tuple       =     sd_pipe([prompt] ,				generator=A_ ,				guidance_scale=6.0 ,				num_inference_steps=2 ,				output_type='''np'''       )

         _lowercase:			Tuple       =     output.images

         _lowercase:			List[str]       =     torch.Generator(device=A_       ).manual_seed(0       )
         _lowercase:			Dict       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=6.0 ,				num_inference_steps=2 ,				output_type='''np''' ,				return_dict=A_ ,				)[0]

         _lowercase:			List[str]       =     image[0, -3:, -3:, -1]
         _lowercase:			Any       =     image_from_tuple[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         _lowercase:			Any       =     np.array([0.51_25, 0.57_16, 0.48_28, 0.50_60, 0.56_50, 0.47_68, 0.51_85, 0.48_95, 0.49_93]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 1E-2
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




         _lowercase:			Tuple       =     StableDiffusionPipeline.from_pretrained(
             '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''' ,				safety_checker=A_       )
         assert isinstance(A_ ,				A_       )
         assert isinstance(pipe.scheduler ,				A_       )
         assert pipe.safety_checker is None

         _lowercase:			Union[str, Any]       =     pipe('''example prompt''' ,				num_inference_steps=2       ).images[0]
         assert image is not None

         # check that there's no error when saving a pipeline with one of the models being None
         with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(A_       )
           _lowercase:			Union[str, Any]       =     StableDiffusionPipeline.from_pretrained(A_       )

         # sanity check that the pipeline still works
         assert pipe.safety_checker is None
         _lowercase:			Optional[int]       =     pipe('''example prompt''' ,				num_inference_steps=2       ).images[0]
         assert image is not None



       @unittest.skipIf(torch_device != '''cuda''' ,				'''This test requires a GPU'''       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			Any       =     self.dummy_cond_unet
         _lowercase:			Optional[Any]       =     PNDMScheduler(skip_prk_steps=A_       )
         _lowercase:			Optional[Any]       =     self.dummy_vae
         _lowercase:			Optional[int]       =     self.dummy_text_encoder
         _lowercase:			List[Any]       =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

         # put models in fp16
         _lowercase:			int       =     unet.half()
         _lowercase:			Optional[Any]       =     vae.half()
         _lowercase:			int       =     bert.half()

         # make sure here that pndm scheduler skips prk
         _lowercase:			List[str]       =     StableDiffusionPipeline(
             unet=A_ ,				scheduler=A_ ,				vae=A_ ,				text_encoder=A_ ,				tokenizer=A_ ,				safety_checker=A_ ,				feature_extractor=self.dummy_extractor ,				)
         _lowercase:			Dict       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			Optional[int]       =     '''A painting of a squirrel eating a burger'''
         _lowercase:			str       =     sd_pipe([prompt] ,				num_inference_steps=2 ,				output_type='''np'''       ).images

         assert image.shape == (1, 64, 64, 3)


@nightly
@require_torch_gpu
class 			__magic_name__       (       unittest.TestCase ):
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' ,				safety_checker=A_       )
         _lowercase:			List[Any]       =     LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config       )
         _lowercase:			Optional[int]       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			List[str]       =     (
             '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'''
             ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'''
             ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'''
             ''' children from bahnhof zoo, detailed '''
         )
         _lowercase:			Optional[int]       =     40_0366_0346
         _lowercase:			Optional[Any]       =     7

         # without safety guidance (sld_guidance_scale = 0)
         _lowercase:			Tuple       =     torch.manual_seed(A_       )
         _lowercase:			str       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=0 ,				)

         _lowercase:			Optional[int]       =     output.images
         _lowercase:			List[Any]       =     image[0, -3:, -3:, -1]
         _lowercase:			int       =     [0.22_78, 0.22_31, 0.22_49, 0.23_33, 0.23_03, 0.18_85, 0.22_73, 0.21_44, 0.21_76]

         assert image.shape == (1, 512, 512, 3)

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

         # without safety guidance (strong configuration)
         _lowercase:			Union[str, Any]       =     torch.manual_seed(A_       )
         _lowercase:			Any       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=2000 ,				sld_warmup_steps=7 ,				sld_threshold=0.0_25 ,				sld_momentum_scale=0.5 ,				sld_mom_beta=0.7 ,				)

         _lowercase:			Union[str, Any]       =     output.images
         _lowercase:			Union[str, Any]       =     image[0, -3:, -3:, -1]
         _lowercase:			int       =     [0.23_83, 0.22_76, 0.2_36, 0.21_92, 0.21_86, 0.20_53, 0.19_71, 0.19_01, 0.17_19]

         assert image.shape == (1, 512, 512, 3)

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
       def 							lowercase_							(     self       )     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			List[str]       =     StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' ,				safety_checker=A_       )
         _lowercase:			int       =     LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config       )
         _lowercase:			int       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			str       =     '''padme amidala taking a bath artwork, safe for work, no nudity'''
         _lowercase:			Union[str, Any]       =     27_3497_1755
         _lowercase:			Tuple       =     7

         _lowercase:			Tuple       =     torch.manual_seed(A_       )
         _lowercase:			Tuple       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=0 ,				)

         _lowercase:			Dict       =     output.images
         _lowercase:			List[str]       =     image[0, -3:, -3:, -1]
         _lowercase:			Optional[Any]       =     [0.35_02, 0.36_22, 0.33_96, 0.36_42, 0.34_78, 0.33_18, 0.35, 0.33_48, 0.32_97]

         assert image.shape == (1, 512, 512, 3)

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

         _lowercase:			List[Any]       =     torch.manual_seed(A_       )
         _lowercase:			List[Any]       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=2000 ,				sld_warmup_steps=7 ,				sld_threshold=0.0_25 ,				sld_momentum_scale=0.5 ,				sld_mom_beta=0.7 ,				)

         _lowercase:			Any       =     output.images
         _lowercase:			List[Any]       =     image[0, -3:, -3:, -1]
         _lowercase:			Optional[Any]       =     [0.55_31, 0.52_06, 0.48_95, 0.51_56, 0.51_82, 0.47_51, 0.48_02, 0.48_03, 0.44_43]

         assert image.shape == (1, 512, 512, 3)

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



       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''       )
         _lowercase:			int       =     sd_pipe.to(A_       )
         sd_pipe.set_progress_bar_config(disable=A_       )

         _lowercase:			Tuple       =     (
             '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'''
             ''' leyendecker'''
         )
         _lowercase:			List[Any]       =     10_4435_5234
         _lowercase:			str       =     12

         _lowercase:			Optional[int]       =     torch.manual_seed(A_       )
         _lowercase:			Dict       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=0 ,				)

         _lowercase:			Tuple       =     output.images
         _lowercase:			Dict       =     image[0, -3:, -3:, -1]
         _lowercase:			Optional[int]       =     np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]       )

         assert image.shape == (1, 512, 512, 3)

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-7

         _lowercase:			Any       =     torch.manual_seed(A_       )
         _lowercase:			Optional[int]       =     sd_pipe(
             [prompt] ,				generator=A_ ,				guidance_scale=A_ ,				num_inference_steps=50 ,				output_type='''np''' ,				width=512 ,				height=512 ,				sld_guidance_scale=2000 ,				sld_warmup_steps=7 ,				sld_threshold=0.0_25 ,				sld_momentum_scale=0.5 ,				sld_mom_beta=0.7 ,				)

         _lowercase:			Optional[int]       =     output.images
         _lowercase:			Union[str, Any]       =     image[0, -3:, -3:, -1]
         _lowercase:			Optional[int]       =     np.array([0.58_18, 0.62_85, 0.68_35, 0.60_19, 0.6_25, 0.67_54, 0.60_96, 0.63_34, 0.65_61]       )
         assert image.shape == (1, 512, 512, 3)

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


"""simple docstring"""




import comet  # From: unbabel-comet
import torch

import datasets


A__   :					int							=   datasets.logging.get_logger(__name__)

A__   :					Optional[Any]							=   '\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = "{COMET}: A Neural Framework for {MT} Evaluation",\n   author = "Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon",\n   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n   month = nov,\n   year = "2020",\n   address = "Online",\n   publisher = "Association for Computational Linguistics",\n   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n   pages = "2685--2702",\n}\n'

A__   :					Union[str, Any]							=   '\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

A__   :					int							=   '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,					_KWARGS_DESCRIPTION )
class 			__magic_name__       (       datasets.Metric ):
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         return datasets.MetricInfo(
             description=_DESCRIPTION ,				citation=_CITATION ,				homepage='''https://unbabel.github.io/COMET/html/index.html''' ,				inputs_description=_KWARGS_DESCRIPTION ,				features=datasets.Features(
                 {
                     '''sources''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''predictions''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''references''': datasets.Value('''string''' ,				id='''sequence'''       ),
                 }       ) ,				codebase_urls=['''https://github.com/Unbabel/COMET'''] ,				reference_urls=[
                 '''https://github.com/Unbabel/COMET''',
                 '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
                 '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
             ] ,				)
       def 							lowercase_							(     self ,				A_       )     ->	Dict:





         """simple docstring"""




         if self.config_name == "default":
           _lowercase:			str       =     comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
         else:
           _lowercase:			Optional[Any]       =     comet.load_from_checkpoint(comet.download_model(self.config_name       )       )



       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_=None ,				A_=False       )     ->	List[str]:





         """simple docstring"""




         if gpus is None:
           _lowercase:			Union[str, Any]       =     1 if torch.cuda.is_available() else 0
         _lowercase:			Any       =     {'''src''': sources, '''mt''': predictions, '''ref''': references}
         _lowercase:			int       =     [dict(zip(A_ ,				A_       )       ) for t in zip(*data.values()       )]
         _lowercase ,				_lowercase:			Tuple       =     self.scorer.predict(A_ ,				gpus=A_ ,				progress_bar=A_       )
         return {"mean_score": mean_score, "scores": scores}
