import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


UpperCamelCase  							=						'''\
@inproceedings{snover-etal-2006-study,
    title = "A Study of Translation Edit Rate with Targeted Human Annotation",
    author = "Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John",
    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",
    month = aug # " 8-12",
    year = "2006",
    address = "Cambridge, Massachusetts, USA",
    publisher = "Association for Machine Translation in the Americas",
    url = "https://aclanthology.org/2006.amta-papers.25",
    pages = "223--231",
}
@inproceedings{post-2018-call,
    title = "A Call for Clarity in Reporting {BLEU} Scores",
    author = "Post, Matt",
    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
    month = oct,
    year = "2018",
    address = "Belgium, Brussels",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W18-6319",
    pages = "186--191",
}
'''

UpperCamelCase  							=						'''\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
'''

UpperCamelCase  							=						'''
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)
    \'num_edits\' (int): The cumulative number of edits
    \'ref_length\' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?",
        ...                     "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}

    Example 2:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}

    Example 3:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}

    Example 4:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}

    Example 5:
        >>> predictions = ["does this sentence match??",
        ...                    "what about this sentence?",
        ...                    "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}
'''



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






   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Tuple:
       if version.parse(scb.__version__  ) < version.parse("1.4.12"  ):
           raise ImportWarning(
               "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
               "You can install it with `pip install \"sacrebleu>=1.4.12\"`."  )
       return datasets.MetricInfo(
           description=_DESCRIPTION	,						citation=_CITATION	,						homepage="http://www.cs.umd.edu/~snover/tercom/"	,						inputs_description=_KWARGS_DESCRIPTION	,						features=datasets.Features(
               {
                   "predictions": datasets.Value("string"	,						id="sequence"  ),
                   "references": datasets.Sequence(datasets.Value("string"	,						id="sequence"  )	,						id="references"  ),
               }  )	,						codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]	,						reference_urls=[
               "https://github.com/jhclark/tercom",
           ]	,						)







   def       __UpperCamelCase     (      self				:     Optional[Any]	,						lowercase_				:     str	,						lowercase_				:     Optional[int]	,						lowercase_				:     bool = False	,						lowercase_				:     bool = False	,						lowercase_				:     bool = False	,						lowercase_				:     bool = False	,						)					->						Any:
       lowercase__ :   Optional[int]    					=				len(references[0]  )
       if any(len(lowercase_  ) != references_per_prediction for refs in references  ):
           raise ValueError("Sacrebleu requires the same number of references for each prediction"  )
       lowercase__ :   Union[str, Any]    					=				[[refs[i] for refs in references] for i in range(lowercase_  )]

       lowercase__ :   str    					=				TER(
           normalized=lowercase_	,						no_punct=lowercase_	,						asian_support=lowercase_	,						case_sensitive=lowercase_	,						)
       lowercase__ :   List[str]    					=				sb_ter.corpus_score(lowercase_	,						lowercase_  )

       return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}







import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

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,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class 	UpperCAmelCase_					(					UpperCamelCase		, UpperCamelCase		, UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      Tuple     		=		StableUnCLIPPipeline
   __A :      Optional[int]     		=		TEXT_TO_IMAGE_PARAMS
   __A :      str     		=		TEXT_TO_IMAGE_BATCH_PARAMS
   __A :      int     		=		TEXT_TO_IMAGE_IMAGE_PARAMS
   __A :      Tuple     		=		TEXT_TO_IMAGE_IMAGE_PARAMS

   # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
   __A :      Union[str, Any]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				32
     lowerCamelCase :					Dict    =				embedder_hidden_size

     # prior components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTextModelWithProjection(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=__A						,				intermediate_size=37						,				layer_norm_eps=1e-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				PriorTransformer(
         num_attention_heads=2						,				attention_head_dim=12						,				embedding_dim=__A						,				num_layers=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Dict    =				DDPMScheduler(
         variance_type="fixed_small_log"						,				prediction_type="sample"						,				num_train_timesteps=1000						,				clip_sample=__A						,				clip_sample_range=5.0						,				beta_schedule="squaredcos_cap_v2"						,				)

     # regular denoising components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				StableUnCLIPImageNormalizer(embedding_dim=__A )
     lowerCamelCase :					Tuple    =				DDPMScheduler(beta_schedule="squaredcos_cap_v2" )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					str    =				CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=32						,				intermediate_size=37						,				layer_norm_eps=1e-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					Any    =				UNetaDConditionModel(
         sample_size=32						,				in_channels=4						,				out_channels=4						,				down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")						,				up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")						,				block_out_channels=(32, 64)						,				attention_head_dim=(2, 4)						,				class_embed_type="projection"						,				projection_class_embeddings_input_dim=embedder_projection_dim * 2						,				cross_attention_dim=__A						,				layers_per_block=1						,				upcast_attention=__A						,				use_linear_projection=__A						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					int    =				DDIMScheduler(
         beta_schedule="scaled_linear"						,				beta_start=0.00085						,				beta_end=0.012						,				prediction_type="v_prediction"						,				set_alpha_to_one=__A						,				steps_offset=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[Any]    =				AutoencoderKL()

     lowerCamelCase :					Optional[int]    =				{
         # prior components
         "prior_tokenizer": prior_tokenizer,
         "prior_text_encoder": prior_text_encoder,
         "prior": prior,
         "prior_scheduler": prior_scheduler,
         # image noising components
         "image_normalizer": image_normalizer,
         "image_noising_scheduler": image_noising_scheduler,
         # regular denoising components
         "tokenizer": tokenizer,
         "text_encoder": text_encoder,
         "unet": unet,
         "scheduler": scheduler,
         "vae": vae,
     }

     return components






   def _snake_case    (		self						,				__A						,				__A=0 ):






     """simple docstring"""





     if str(__A ).startswith("mps" ):
       lowerCamelCase :					Optional[int]    =				torch.manual_seed(__A )
     else:
       lowerCamelCase :					Optional[Any]    =				torch.Generator(device=__A ).manual_seed(__A )
     lowerCamelCase :					Tuple    =				{
         "prompt": "A painting of a squirrel eating a burger",
         "generator": generator,
         "num_inference_steps": 2,
         "prior_num_inference_steps": 2,
         "output_type": "numpy",
     }
     return inputs






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				torch_device in ["cpu", "mps"]

     self._test_inference_batch_single_identical(test_max_difference=__A )



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

   '''simple docstring'''




   def _snake_case    (		self ):






     """simple docstring"""





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






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" )

     lowerCamelCase :					str    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					List[Any]    =				torch.Generator(device="cpu" ).manual_seed(0 )
     lowerCamelCase :					Dict    =				pipe("anime turle"						,				generator=__A						,				output_type="np" )

     lowerCamelCase :					Dict    =				output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

     lowerCamelCase :					int    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     lowerCamelCase :					Union[str, Any]    =				pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					Any    =				pipe(
         "anime turtle"						,				prior_num_inference_steps=2						,				num_inference_steps=2						,				output_type="np"						,				)

     lowerCamelCase :					List[str]    =				torch.cuda.max_memory_allocated()
     # make sure that less than 7 GB is allocated
     assert mem_bytes < 7 * 10**9



