

import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class 						__magic_name__    (       _snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						DiTPipeline
 UpperCAmelCase							    =						CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
 UpperCAmelCase							    =						PipelineTesterMixin.required_optional_params - {
     """latents""",
     """num_images_per_prompt""",
     """callback""",
     """callback_steps""",
 }
 UpperCAmelCase							    =						CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
 UpperCAmelCase							    =						False


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Any:
   torch.manual_seed(0    )
   UpperCAmelCase					      =  TransformeraDModel(
       sample_size=1_6			,						num_layers=2			,						patch_size=4			,						attention_head_dim=8			,						num_attention_heads=2			,						in_channels=4			,						out_channels=8			,						attention_bias=lowerCAmelCase__			,						activation_fn="gelu-approximate"			,						num_embeds_ada_norm=1_0_0_0			,						norm_type="ada_norm_zero"			,						norm_elementwise_affine=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  AutoencoderKL()
   UpperCAmelCase					      =  DDIMScheduler()
   UpperCAmelCase					      =  {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler}
   return components


 def _UpperCamelCase	(						self		: int			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: List[Any]=0    )    ->      Tuple:
   if str(lowerCAmelCase__    ).startswith("mps"    ):
     UpperCAmelCase					      =  torch.manual_seed(lowerCAmelCase__    )
   else:
     UpperCAmelCase					      =  torch.Generator(device=lowerCAmelCase__    ).manual_seed(lowerCAmelCase__    )
   UpperCAmelCase					      =  {
       "class_labels": [1],
       "generator": generator,
       "num_inference_steps": 2,
       "output_type": "numpy",
   }
   return inputs


 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      Any:
   UpperCAmelCase					      =  "cpu"

   UpperCAmelCase					      =  self.get_dummy_components()
   UpperCAmelCase					      =  self.pipeline_class(**lowerCAmelCase__    )
   pipe.to(lowerCAmelCase__    )
   pipe.set_progress_bar_config(disable=lowerCAmelCase__    )

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

   self.assertEqual(image.shape			,						(1, 1_6, 1_6, 3)    )
   UpperCAmelCase					      =  np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457]    )
   UpperCAmelCase					      =  np.abs(image_slice.flatten() - expected_slice    ).max()
   self.assertLessEqual(lowerCAmelCase__			,						1e-3    )


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Union[str, Any]:
   self._test_inference_batch_single_identical(relax_max_difference=lowerCAmelCase__			,						expected_max_diff=1e-3    )


 @unittest.skipIf(
     torch_device != "cuda" or not is_xformers_available()			,						reason="XFormers attention is only available with CUDA and `xformers` installed"			,						)
 def _UpperCamelCase	(						self		: Any    )    ->      str:
   self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )






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


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


 def _UpperCamelCase	(						self		: List[str]    )    ->      Optional[Any]:
   UpperCAmelCase					      =  torch.manual_seed(0    )

   UpperCAmelCase					      =  DiTPipeline.from_pretrained("facebook/DiT-XL-2-256"    )
   pipe.to("cuda"    )

   UpperCAmelCase					      =  ["vase", "umbrella", "white shark", "white wolf"]
   UpperCAmelCase					      =  pipe.get_label_ids(lowerCAmelCase__    )

   UpperCAmelCase					      =  pipe(lowerCAmelCase__			,						generator=lowerCAmelCase__			,						num_inference_steps=4_0			,						output_type="np"    ).images

   for word, image in zip(lowerCAmelCase__			,						lowerCAmelCase__    ):
     UpperCAmelCase					      =  load_numpy(
         f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy"    )
     assert np.abs((expected_image - image).max()    ) < 1e-2


 def _UpperCamelCase	(						self		: Optional[int]    )    ->      List[Any]:
   UpperCAmelCase					      =  DiTPipeline.from_pretrained("facebook/DiT-XL-2-512"    )
   UpperCAmelCase					      =  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
   pipe.to("cuda"    )

   UpperCAmelCase					      =  ["vase", "umbrella"]
   UpperCAmelCase					      =  pipe.get_label_ids(lowerCAmelCase__    )

   UpperCAmelCase					      =  torch.manual_seed(0    )
   UpperCAmelCase					      =  pipe(lowerCAmelCase__			,						generator=lowerCAmelCase__			,						num_inference_steps=2_5			,						output_type="np"    ).images

   for word, image in zip(lowerCAmelCase__			,						lowerCAmelCase__    ):
     UpperCAmelCase					      =  load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         f"/dit/{word}_512.npy"    )

     assert np.abs((expected_image - image).max()    ) < 1e-1






import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase__       = version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
      from nltk import word_tokenize


lowerCAmelCase__       = "\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n"

lowerCAmelCase__       = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"

lowerCAmelCase__       = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    'meteor': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric('meteor')\n    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results[\"meteor\"], 4))\n    0.6944\n"






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


 def _UpperCamelCase	(						self		: int    )    ->      str:
   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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"]			,						reference_urls=[
           "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score",
           "https://en.wikipedia.org/wiki/METEOR",
       ]			,						)


 def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: List[Any]    )    ->      Dict:
   import nltk

   nltk.download("wordnet"    )
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     nltk.download("punkt"    )
   if NLTK_VERSION >= version.Version("3.6.6"    ):
     nltk.download("omw-1.4"    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Any=0.9			,						lowerCAmelCase__		: Tuple=3			,						lowerCAmelCase__		: Optional[int]=0.5    )    ->      Any:
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(
             word_tokenize(lowerCAmelCase__    )			,						word_tokenize(lowerCAmelCase__    )			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]
   else:
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(lowerCAmelCase__			,						lowerCAmelCase__			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]

   return {"meteor": np.mean(lowerCAmelCase__    )}



