import os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
	import jax
	import jax.numpy as jnp
	from flax.jax_utils import replicate
	from flax.training.common_utils import shard

	from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline

@require_flax
class        UpperCamelCase						(				unittest.TestCase				):





						def        A_							(self						)				->				Union[str, Any]:
												with tempfile.TemporaryDirectory() as tmpdirname:
																		# pipeline has Flax weights
																		UpperCamelCase_		:							List[Any]  =		FlaxDiffusionPipeline.from_pretrained(
																		    """hf-internal-testing/tiny-stable-diffusion-pipe"""			,     safety_checker=__UpperCamelCase			,     cache_dir=__UpperCamelCase						)

																		UpperCamelCase_		:							List[Any]  =		[t[-1] for t in os.walk(os.path.join(__UpperCamelCase			,     os.listdir(__UpperCamelCase						)[0]			,     """snapshots"""						)						)]
																		UpperCamelCase_		:							Tuple  =		[item for sublist in all_root_files for item in sublist]

																		# None of the downloaded files should be a PyTorch file even if we have some here:
																		# https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
																		assert not any(f.endswith(""".bin"""						) for f in files						)


@slow
@require_flax
class        UpperCamelCase						(				unittest.TestCase				):





						def        A_							(self						)				->				Union[str, Any]:
												UpperCamelCase_,UpperCamelCase_		:							Tuple  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """hf-internal-testing/tiny-stable-diffusion-pipe"""			,     safety_checker=__UpperCamelCase						)

												UpperCamelCase_		:							str  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							str  =		jax.random.PRNGKey(0						)
												UpperCamelCase_		:							int  =		4

												UpperCamelCase_		:							Union[str, Any]  =		jax.device_count()
												UpperCamelCase_		:							int  =		num_samples * [prompt]
												UpperCamelCase_		:							Any  =		pipeline.prepare_inputs(__UpperCamelCase						)

												# shard inputs and rng
												UpperCamelCase_		:							str  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							str  =		jax.random.split(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							List[str]  =		shard(__UpperCamelCase						)

												UpperCamelCase_		:							Tuple  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images

												assert images.shape == (num_samples, 1, 64, 64, 3)
												if jax.device_count() == 8:
																		assert np.abs(np.abs(images[0, 0, :2, :2, -2:]			,     dtype=np.floataa						).sum() - 4.1_514_745						) < 1E-3
																		assert np.abs(np.abs(__UpperCamelCase			,     dtype=np.floataa						).sum() - 49_947.875						) < 5E-1

												UpperCamelCase_		:							Union[str, Any]  =		pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]						)						)						)
												assert len(__UpperCamelCase						) == num_samples





						def        A_							(self						)				->				int:
												UpperCamelCase_,UpperCamelCase_		:							Optional[Any]  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""flax"""			,     safety_checker=__UpperCamelCase						)

												UpperCamelCase_		:							str  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							Optional[Any]  =		jax.random.PRNGKey(0						)
												UpperCamelCase_		:							List[str]  =		50

												UpperCamelCase_		:							Tuple  =		jax.device_count()
												UpperCamelCase_		:							Optional[Any]  =		num_samples * [prompt]
												UpperCamelCase_		:							Tuple  =		pipeline.prepare_inputs(__UpperCamelCase						)

												# shard inputs and rng
												UpperCamelCase_		:							Tuple  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							Optional[int]  =		jax.random.split(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							Dict  =		shard(__UpperCamelCase						)

												UpperCamelCase_		:							int  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images

												assert images.shape == (num_samples, 1, 512, 512, 3)
												if jax.device_count() == 8:
																		assert np.abs((np.abs(images[0, 0, :2, :2, -2:]			,     dtype=np.floataa						).sum() - 0.05_652_401)						) < 1E-3
																		assert np.abs((np.abs(__UpperCamelCase			,     dtype=np.floataa						).sum() - 2_383_808.2)						) < 5E-1





						def        A_							(self						)				->				Optional[Any]:
												UpperCamelCase_,UpperCamelCase_		:							str  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""bf16"""			,     dtype=jnp.bfloataa			,     safety_checker=__UpperCamelCase						)

												UpperCamelCase_		:							List[str]  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							Union[str, Any]  =		jax.random.PRNGKey(0						)
												UpperCamelCase_		:							Any  =		50

												UpperCamelCase_		:							int  =		jax.device_count()
												UpperCamelCase_		:							Dict  =		num_samples * [prompt]
												UpperCamelCase_		:							Dict  =		pipeline.prepare_inputs(__UpperCamelCase						)

												# shard inputs and rng
												UpperCamelCase_		:							List[str]  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							Optional[int]  =		jax.random.split(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							str  =		shard(__UpperCamelCase						)

												UpperCamelCase_		:							List[str]  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images

												assert images.shape == (num_samples, 1, 512, 512, 3)
												if jax.device_count() == 8:
																		assert np.abs((np.abs(images[0, 0, :2, :2, -2:]			,     dtype=np.floataa						).sum() - 0.04_003_906)						) < 1E-3
																		assert np.abs((np.abs(__UpperCamelCase			,     dtype=np.floataa						).sum() - 2_373_516.75)						) < 5E-1





						def        A_							(self						)				->				Tuple:
												UpperCamelCase_,UpperCamelCase_		:							List[str]  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""bf16"""			,     dtype=jnp.bfloataa						)

												UpperCamelCase_		:							Optional[Any]  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							Union[str, Any]  =		jax.random.PRNGKey(0						)
												UpperCamelCase_		:							Optional[Any]  =		50

												UpperCamelCase_		:							str  =		jax.device_count()
												UpperCamelCase_		:							str  =		num_samples * [prompt]
												UpperCamelCase_		:							Dict  =		pipeline.prepare_inputs(__UpperCamelCase						)

												# shard inputs and rng
												UpperCamelCase_		:							Optional[Any]  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							Tuple  =		jax.random.split(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							Union[str, Any]  =		shard(__UpperCamelCase						)

												UpperCamelCase_		:							List[Any]  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images

												assert images.shape == (num_samples, 1, 512, 512, 3)
												if jax.device_count() == 8:
																		assert np.abs((np.abs(images[0, 0, :2, :2, -2:]			,     dtype=np.floataa						).sum() - 0.04_003_906)						) < 1E-3
																		assert np.abs((np.abs(__UpperCamelCase			,     dtype=np.floataa						).sum() - 2_373_516.75)						) < 5E-1





						def        A_							(self						)				->				Optional[int]:
												UpperCamelCase_		:							int  =		FlaxDDIMScheduler(
												    beta_start=0.00_085			,     beta_end=0.012			,     beta_schedule="""scaled_linear"""			,     set_alpha_to_one=__UpperCamelCase			,     steps_offset=1			,     )

												UpperCamelCase_,UpperCamelCase_		:							Dict  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""bf16"""			,     dtype=jnp.bfloataa			,     scheduler=__UpperCamelCase			,     safety_checker=__UpperCamelCase			,     )
												UpperCamelCase_		:							str  =		scheduler.create_state()

												UpperCamelCase_		:							Optional[int]  =		scheduler_state

												UpperCamelCase_		:							Union[str, Any]  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							Union[str, Any]  =		jax.random.PRNGKey(0						)
												UpperCamelCase_		:							Optional[Any]  =		50

												UpperCamelCase_		:							Any  =		jax.device_count()
												UpperCamelCase_		:							int  =		num_samples * [prompt]
												UpperCamelCase_		:							Optional[Any]  =		pipeline.prepare_inputs(__UpperCamelCase						)

												# shard inputs and rng
												UpperCamelCase_		:							str  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							Union[str, Any]  =		jax.random.split(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							Any  =		shard(__UpperCamelCase						)

												UpperCamelCase_		:							int  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images

												assert images.shape == (num_samples, 1, 512, 512, 3)
												if jax.device_count() == 8:
																		assert np.abs((np.abs(images[0, 0, :2, :2, -2:]			,     dtype=np.floataa						).sum() - 0.045_043_945)						) < 1E-3
																		assert np.abs((np.abs(__UpperCamelCase			,     dtype=np.floataa						).sum() - 2_347_693.5)						) < 5E-1





						def        A_							(self						)				->				Tuple:
												UpperCamelCase_		:							Optional[Any]  =		(
												    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
												    """ field, close up, split lighting, cinematic"""
												)

												UpperCamelCase_		:							Any  =		jax.device_count()
												UpperCamelCase_		:							Optional[Any]  =		num_samples * [prompt]
												UpperCamelCase_		:							int  =		jax.random.split(jax.random.PRNGKey(0						)			,     __UpperCamelCase						)

												UpperCamelCase_,UpperCamelCase_		:							str  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""bf16"""			,     dtype=jnp.bfloataa			,     safety_checker=__UpperCamelCase			,     )

												UpperCamelCase_		:							Any  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							List[Any]  =		pipeline.prepare_inputs(__UpperCamelCase						)
												UpperCamelCase_		:							Optional[int]  =		shard(__UpperCamelCase						)
												UpperCamelCase_		:							Optional[Any]  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images
												assert images.shape == (num_samples, 1, 512, 512, 3)
												UpperCamelCase_		:							int  =		images[2, 0, 256, 10:17, 1]

												# With memory efficient attention
												UpperCamelCase_,UpperCamelCase_		:							Union[str, Any]  =		FlaxStableDiffusionPipeline.from_pretrained(
												    """CompVis/stable-diffusion-v1-4"""			,     revision="""bf16"""			,     dtype=jnp.bfloataa			,     safety_checker=__UpperCamelCase			,     use_memory_efficient_attention=__UpperCamelCase			,     )

												UpperCamelCase_		:							Dict  =		replicate(__UpperCamelCase						)
												UpperCamelCase_		:							Any  =		pipeline.prepare_inputs(__UpperCamelCase						)
												UpperCamelCase_		:							Union[str, Any]  =		shard(__UpperCamelCase						)
												UpperCamelCase_		:							Tuple  =		pipeline(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     jit=__UpperCamelCase						).images
												assert images_eff.shape == (num_samples, 1, 512, 512, 3)
												UpperCamelCase_		:							str  =		images[2, 0, 256, 10:17, 1]

												# I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
												# over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
												assert abs(slice_eff - slice						).max() < 1E-2







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

import datasets


SCREAMING_SNAKE_CASE		:     Tuple         =	"\\n@inproceedings{popovic-2015-chrf,\n    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n    month = sep,\n    year = \"2015\",\n    address = \"Lisbon, Portugal\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W15-3049\",\n    doi = \"10.18653/v1/W15-3049\",\n    pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n    title = \"chr{F}++: words helping character n-grams\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n    month = sep,\n    year = \"2017\",\n    address = \"Copenhagen, Denmark\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W17-4770\",\n    doi = \"10.18653/v1/W17-4770\",\n    pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

SCREAMING_SNAKE_CASE		:     Tuple         =	"\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

SCREAMING_SNAKE_CASE		:     Optional[int]         =	"\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"

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





						def        A_							(self						)				->				Dict:
												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			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase = CHRF.CHAR_ORDER			,     __UpperCamelCase = CHRF.WORD_ORDER			,     __UpperCamelCase = CHRF.BETA			,     __UpperCamelCase = False			,     __UpperCamelCase = False			,     __UpperCamelCase = False			,     )				->				List[Any]:
												UpperCamelCase_		:							List[str]  =		len(references[0]						)
												if any(len(__UpperCamelCase						) != references_per_prediction for refs in references						):
																		raise ValueError("""Sacrebleu requires the same number of references for each prediction"""						)
												UpperCamelCase_		:							Optional[Any]  =		[[refs[i] for refs in references] for i in range(__UpperCamelCase						)]

												UpperCamelCase_		:							List[Any]  =		CHRF(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							int  =		sb_chrf.corpus_score(__UpperCamelCase			,     __UpperCamelCase						)

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






