






import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class    _lowerCAmelCase			(		lowercase_     ,      unittest.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Any      =  LDMTextToImagePipeline
				_lowercase				:   int      =  TEXT_TO_IMAGE_PARAMS - {
				    '''negative_prompt''',
				    '''negative_prompt_embeds''',
				    '''cross_attention_kwargs''',
				    '''prompt_embeds''',
				}
				_lowercase				:   int      =  PipelineTesterMixin.required_optional_params - {
				    '''num_images_per_prompt''',
				    '''callback''',
				    '''callback_steps''',
				}
				_lowercase				:   Optional[int]      =  TEXT_TO_IMAGE_BATCH_PARAMS
				_lowercase				:   Any      =  False



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											torch.manual_seed(0)
											snake_case__	  =       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			,		)
											snake_case__	  =       DDIMScheduler(
											    beta_start=0.0_00_85			,		beta_end=0.0_12			,		beta_schedule="""scaled_linear"""			,		clip_sample=UpperCamelCase__			,		set_alpha_to_one=UpperCamelCase__			,		)
											torch.manual_seed(0)
											snake_case__	  =       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			,		)
											torch.manual_seed(0)
											snake_case__	  =       CLIPTextConfig(
											    bos_token_id=0			,		eos_token_id=2			,		hidden_size=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=1_0_0_0			,		)
											snake_case__	  =       CLIPTextModel(UpperCamelCase__)
											snake_case__	  =       CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

											snake_case__	  =       {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vqvae""": vae,
											    """bert""": text_encoder,
											    """tokenizer""": tokenizer,
											}
											return components



				def 					__magic_name__							(      self    :    Any			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Optional[Any]=0):






											'''simple docstring'''







											if str(UpperCamelCase__).startswith("""mps"""):
																		snake_case__	  =       torch.manual_seed(UpperCamelCase__)
											else:
																		snake_case__	  =       torch.Generator(device=UpperCamelCase__).manual_seed(UpperCamelCase__)
											snake_case__	  =       {
											    """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 					__magic_name__							(      self    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       """cpu"""  # ensure determinism for the device-dependent torch.Generator

											snake_case__	  =       self.get_dummy_components()
											snake_case__	  =       LDMTextToImagePipeline(**UpperCamelCase__)
											pipe.to(UpperCamelCase__)
											pipe.set_progress_bar_config(disable=UpperCamelCase__)

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

											assert image.shape == (1, 1_6, 1_6, 3)
											snake_case__	  =       np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14])

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


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



				"""simple docstring"""



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







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



				def 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    int=torch.floataa			,		UpperCamelCase__    :    Tuple=0):






											'''simple docstring'''







											snake_case__	  =       torch.manual_seed(UpperCamelCase__)
											snake_case__	  =       np.random.RandomState(UpperCamelCase__).standard_normal((1, 4, 3_2, 3_2))
											snake_case__	  =       torch.from_numpy(UpperCamelCase__).to(device=UpperCamelCase__			,		dtype=UpperCamelCase__)
											snake_case__	  =       {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 3,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs



				def 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







											snake_case__	  =       LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(UpperCamelCase__)
											pipe.set_progress_bar_config(disable=UpperCamelCase__)

											snake_case__	  =       self.get_inputs(UpperCamelCase__)
											snake_case__	  =       pipe(**UpperCamelCase__).images
											snake_case__	  =       image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 2_5_6, 2_5_6, 3)
											snake_case__	  =       np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78])
											snake_case__	  =       np.abs(expected_slice - image_slice).max()
											assert max_diff < 1E-3


@nightly
@require_torch_gpu
class    _lowerCAmelCase			(		unittest.TestCase      ):



				"""simple docstring"""



				def 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







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



				def 					__magic_name__							(      self    :    Optional[int]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    Optional[Any]=torch.floataa			,		UpperCamelCase__    :    int=0):






											'''simple docstring'''







											snake_case__	  =       torch.manual_seed(UpperCamelCase__)
											snake_case__	  =       np.random.RandomState(UpperCamelCase__).standard_normal((1, 4, 3_2, 3_2))
											snake_case__	  =       torch.from_numpy(UpperCamelCase__).to(device=UpperCamelCase__			,		dtype=UpperCamelCase__)
											snake_case__	  =       {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 5_0,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(UpperCamelCase__)
											pipe.set_progress_bar_config(disable=UpperCamelCase__)

											snake_case__	  =       self.get_inputs(UpperCamelCase__)
											snake_case__	  =       pipe(**UpperCamelCase__).images[0]

											snake_case__	  =       load_numpy(
											    """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""")
											snake_case__	  =       np.abs(expected_image - image).max()
											assert max_diff < 1E-3








import comet  # From: unbabel-comet
import torch

import datasets


a__       =     datasets.logging.get_logger(__name__)

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

a__       =     """\
Crosslingual 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).
With 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.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
"""

a__       =     """
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric('comet')
    >>> # comet_metric = load_metric('comet', 'wmt20-comet-da')  # you can also choose which model to use
    >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"]
    >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"]
    >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results[\"scores\"]])
    [0.19, 0.92]
"""


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



				"""simple docstring"""



				def 					__magic_name__							(      self    :    Optional[Any]):






											'''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 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    Dict):






											'''simple docstring'''







											if self.config_name == "default":
																		snake_case__	  =       comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""))
											else:
																		snake_case__	  =       comet.load_from_checkpoint(comet.download_model(self.config_name))



				def 					__magic_name__							(      self    :    List[str]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    int=None			,		UpperCamelCase__    :    List[Any]=False):






											'''simple docstring'''







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