



import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


lowerCAmelCase__		:					List[str]							='''\
@inproceedings{popovic-2015-chrf,
    title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation",
    author = "Popovi{\'c}, Maja",
    booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation",
    month = sep,
    year = "2015",
    address = "Lisbon, Portugal",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/W15-3049",
    doi = "10.18653/v1/W15-3049",
    pages = "392--395",
}
@inproceedings{popovic-2017-chrf,
    title = "chr{F}++: words helping character n-grams",
    author = "Popovi{\'c}, Maja",
    booktitle = "Proceedings of the Second Conference on Machine Translation",
    month = sep,
    year = "2017",
    address = "Copenhagen, Denmark",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/W17-4770",
    doi = "10.18653/v1/W17-4770",
    pages = "612--618",
}
@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",
}
'''

lowerCAmelCase__		:					Any							='''\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

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#chrf--chrf for more information.
'''

lowerCAmelCase__		:					List[str]							='''
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    \'score\' (float): The chrF (chrF++) score,
    \'char_order\' (int): The character n-gram order,
    \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    \'beta\' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
        >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
        >>> chrf = datasets.load_metric("chrf")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
        >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
        >>> chrf = datasets.load_metric("chrf")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."]
        >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]]
        >>> chrf = datasets.load_metric("chrf")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2}
'''

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

						'''simple docstring'''




						def 	_A     (   self		):







													'''simple docstring'''

													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='https://github.com/mjpost/sacreBLEU#chrf--chrf'				,							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#chrf--chrf']				,							reference_urls=[
													        'https://github.com/m-popovic/chrF',
													    ]				,							)






						def 	_A     (   self				,							_A				,							_A				,							_A = CHRF.CHAR_ORDER				,							_A = CHRF.WORD_ORDER				,							_A = CHRF.BETA				,							_A = False				,							_A = False				,							_A = False				,							):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= len(references[0]		)
													if any(len(_A		) != references_per_prediction for refs in references		):
																				raise ValueError('Sacrebleu requires the same number of references for each prediction'		)
													__SCREAMING_SNAKE_CASE									= [[refs[i] for refs in references] for i in range(_A		)]

													__SCREAMING_SNAKE_CASE									= CHRF(_A				,							_A				,							_A				,							_A				,							_A				,							_A		)
													__SCREAMING_SNAKE_CASE									= sb_chrf.corpus_score(_A				,							_A		)

													return {
													    "score": output.score,
													    "char_order": output.char_order,
													    "word_order": output.word_order,
													    "beta": output.beta,
													}











import gc
import random
import unittest

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

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class        UpperCAmelCase_  (       UpperCamelCase_   ,   UpperCamelCase_   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			List[str]      =  CycleDiffusionPipeline
						UpperCamelCase__      :			int      =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
						    '''negative_prompt''',
						    '''height''',
						    '''width''',
						    '''negative_prompt_embeds''',
						}
						UpperCamelCase__      :			Union[str, Any]      =  PipelineTesterMixin.required_optional_params - {'''latents'''}
						UpperCamelCase__      :			List[str]      =  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}	)
						UpperCamelCase__      :			Optional[int]      =  IMAGE_TO_IMAGE_IMAGE_PARAMS
						UpperCamelCase__      :			str      =  IMAGE_TO_IMAGE_IMAGE_PARAMS






						def 	_A     (   self		):







													'''simple docstring'''

													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= 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				,							)
													__SCREAMING_SNAKE_CASE									= DDIMScheduler(
													    beta_start=0.0_0_0_8_5				,							beta_end=0.0_1_2				,							beta_schedule='scaled_linear'				,							num_train_timesteps=1_000				,							clip_sample=_A				,							set_alpha_to_one=_A				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= 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				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= 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=1_000				,							)
													__SCREAMING_SNAKE_CASE									= CLIPTextModel(_A		)
													__SCREAMING_SNAKE_CASE									= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

													__SCREAMING_SNAKE_CASE									= {
													    'unet': unet,
													    'scheduler': scheduler,
													    'vae': vae,
													    'text_encoder': text_encoder,
													    'tokenizer': tokenizer,
													    'safety_checker': None,
													    'feature_extractor': None,
													}
													return components






						def 	_A     (   self				,							_A				,							_A=0		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= floats_tensor((1, 3, 32, 32)				,							rng=random.Random(_A		)		).to(_A		)
													__SCREAMING_SNAKE_CASE									= image / 2 + 0.5
													if str(_A		).startswith('mps'		):
																				__SCREAMING_SNAKE_CASE									= torch.manual_seed(_A		)
													else:
																				__SCREAMING_SNAKE_CASE									= torch.Generator(device=_A		).manual_seed(_A		)
													__SCREAMING_SNAKE_CASE									= {
													    'prompt': 'An astronaut riding an elephant',
													    'source_prompt': 'An astronaut riding a horse',
													    'image': image,
													    'generator': generator,
													    'num_inference_steps': 2,
													    'eta': 0.1,
													    'strength': 0.8,
													    'guidance_scale': 3,
													    'source_guidance_scale': 1,
													    'output_type': 'numpy',
													}
													return inputs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 'cpu'  # ensure determinism for the device-dependent torch.Generator

													__SCREAMING_SNAKE_CASE									= self.get_dummy_components()
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline(**_A		)
													__SCREAMING_SNAKE_CASE									= pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_dummy_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		)
													__SCREAMING_SNAKE_CASE									= output.images

													__SCREAMING_SNAKE_CASE									= images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.4_4_5_9, 0.4_9_4_3, 0.4_5_4_4, 0.6_6_4_3, 0.5_4_7_4, 0.4_3_2_7, 0.5_7_0_1, 0.5_9_5_9, 0.5_1_7_9]		)

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






						@unittest.skipIf(torch_device != 'cuda'				,							'This test requires a GPU'		)
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.get_dummy_components()
													for name, module in components.items():
																				if hasattr(_A				,							'half'		):
																											__SCREAMING_SNAKE_CASE									= module.half()
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline(**_A		)
													__SCREAMING_SNAKE_CASE									= pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_dummy_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		)
													__SCREAMING_SNAKE_CASE									= output.images

													__SCREAMING_SNAKE_CASE									= images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.3_5_0_6, 0.4_5_4_3, 0.4_4_6, 0.4_5_7_5, 0.5_1_9_5, 0.4_1_5_5, 0.5_2_7_3, 0.5_1_8, 0.4_1_1_6]		)

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






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_save_load_local()






						@unittest.skip('non-deterministic pipeline'		)
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_inference_batch_single_identical()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_dict_tuple_outputs_equivalent()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_save_load_optional_components()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_attention_slicing_forward_pass()







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

						'''simple docstring'''




						def 	_A     (   self		):







													'''simple docstring'''

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






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/cycle-diffusion/black_colored_car.png'		)
													__SCREAMING_SNAKE_CASE									= load_numpy(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'		)
													__SCREAMING_SNAKE_CASE									= init_image.resize((512, 512)		)

													__SCREAMING_SNAKE_CASE									= 'CompVis/stable-diffusion-v1-4'
													__SCREAMING_SNAKE_CASE									= DDIMScheduler.from_pretrained(_A				,							subfolder='scheduler'		)
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline.from_pretrained(
													    _A				,							scheduler=_A				,							safety_checker=_A				,							torch_dtype=torch.floataa				,							revision='fp16'		)

													pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)
													pipe.enable_attention_slicing()

													__SCREAMING_SNAKE_CASE									= 'A black colored car'
													__SCREAMING_SNAKE_CASE									= 'A blue colored car'

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= pipe(
													    prompt=_A				,							source_prompt=_A				,							image=_A				,							num_inference_steps=100				,							eta=0.1				,							strength=0.8_5				,							guidance_scale=3				,							source_guidance_scale=1				,							generator=_A				,							output_type='np'				,							)
													__SCREAMING_SNAKE_CASE									= output.images

													# the values aren't exactly equal, but the images look the same visually
													assert np.abs(image - expected_image		).max() < 5e-1






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/cycle-diffusion/black_colored_car.png'		)
													__SCREAMING_SNAKE_CASE									= load_numpy(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'		)
													__SCREAMING_SNAKE_CASE									= init_image.resize((512, 512)		)

													__SCREAMING_SNAKE_CASE									= 'CompVis/stable-diffusion-v1-4'
													__SCREAMING_SNAKE_CASE									= DDIMScheduler.from_pretrained(_A				,							subfolder='scheduler'		)
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline.from_pretrained(_A				,							scheduler=_A				,							safety_checker=_A		)

													pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)
													pipe.enable_attention_slicing()

													__SCREAMING_SNAKE_CASE									= 'A black colored car'
													__SCREAMING_SNAKE_CASE									= 'A blue colored car'

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= pipe(
													    prompt=_A				,							source_prompt=_A				,							image=_A				,							num_inference_steps=100				,							eta=0.1				,							strength=0.8_5				,							guidance_scale=3				,							source_guidance_scale=1				,							generator=_A				,							output_type='np'				,							)
													__SCREAMING_SNAKE_CASE									= output.images

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






