



"""simple docstring"""







import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
							import onnxruntime as ort
class        __A       (	A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Any   	=				"ssube/stable-diffusion-x4-upscaler-onnx"







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  Any=0						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			floats_tensor((1, 3, 128, 128)			,rng=random.Random(_snake_case						)						)
				lowercase__   :    Union[str, Any]				=			torch.manual_seed(_snake_case						)
				lowercase__   :    List[Any]				=			{
				    '''prompt''': '''A painting of a squirrel eating a burger''',
				    '''image''': image,
				    '''generator''': generator,
				    '''num_inference_steps''': 3,
				    '''guidance_scale''': 7.5,
				    '''output_type''': '''numpy''',
				}
				return inputs







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    Dict				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,provider='''CPUExecutionProvider'''						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    List[Any]				=			self.get_dummy_inputs()
				lowercase__   :    Union[str, Any]				=			pipe(**_snake_case						).images
				lowercase__   :    Optional[int]				=			image[0, -3:, -3:, -1].flatten()

				# started as 128, should now be 512
				assert image.shape == (1, 512, 512, 3)
				lowercase__   :    List[str]				=			np.array(
				    [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]						)
				assert np.abs(image_slice - expected_slice						).max() < 1e-1







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,provider='''CPUExecutionProvider'''						)
				lowercase__   :    List[str]				=			PNDMScheduler.from_config(pipe.scheduler.config			,skip_prk_steps=_snake_case						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    List[Any]				=			self.get_dummy_inputs()
				lowercase__   :    Optional[Any]				=			pipe(**_snake_case						).images
				lowercase__   :    int				=			image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				lowercase__   :    Any				=			np.array(
				    [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964]						)
				assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    Dict				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,provider='''CPUExecutionProvider'''						)
				lowercase__   :    int				=			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    Union[str, Any]				=			self.get_dummy_inputs()
				lowercase__   :    str				=			pipe(**_snake_case						).images
				lowercase__   :    Dict				=			image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				lowercase__   :    Tuple				=			np.array(
				    [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515]						)

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







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,provider='''CPUExecutionProvider'''						)
				lowercase__   :    Union[str, Any]				=			EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    Optional[Any]				=			self.get_dummy_inputs()
				lowercase__   :    Any				=			pipe(**_snake_case						).images
				lowercase__   :    Union[str, Any]				=			image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				lowercase__   :    List[str]				=			np.array(
				    [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]						)
				assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    Dict				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,provider='''CPUExecutionProvider'''						)
				lowercase__   :    int				=			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    List[str]				=			self.get_dummy_inputs()
				lowercase__   :    int				=			pipe(**_snake_case						).images
				lowercase__   :    Union[str, Any]				=			image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				lowercase__   :    Union[str, Any]				=			np.array(
				    [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043]						)

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





@nightly
@require_onnxruntime
@require_torch_gpu
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@property
		def 					UpperCAmelCase    (	self						:  int						)					->		List[str]:






				"""simple docstring"""



				return (
				    "CUDAExecutionProvider",
				    {
				        "gpu_mem_limit": "15000000000",  # 15GB
				        "arena_extend_strategy": "kSameAsRequested",
				    },
				)







		@property
		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		Any:






				"""simple docstring"""



				lowercase__   :    List[str]				=			ort.SessionOptions()
				lowercase__   :    Optional[Any]				=			False
				return options







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		str:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			load_image(
				    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
				    '''/img2img/sketch-mountains-input.jpg'''						)
				lowercase__   :    int				=			init_image.resize((128, 128)						)
				# using the PNDM scheduler by default
				lowercase__   :    Tuple				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(
				    '''ssube/stable-diffusion-x4-upscaler-onnx'''			,provider=self.gpu_provider			,sess_options=self.gpu_options			,)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    Any				=			'''A fantasy landscape, trending on artstation'''

				lowercase__   :    Union[str, Any]				=			torch.manual_seed(0						)
				lowercase__   :    Tuple				=			pipe(
				    prompt=_snake_case			,image=_snake_case			,guidance_scale=7.5			,num_inference_steps=10			,generator=_snake_case			,output_type='''np'''			,)
				lowercase__   :    Tuple				=			output.images
				lowercase__   :    List[Any]				=			images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 512, 3)
				lowercase__   :    Any				=			np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]						)
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    str				=			load_image(
				    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
				    '''/img2img/sketch-mountains-input.jpg'''						)
				lowercase__   :    List[str]				=			init_image.resize((128, 128)						)
				lowercase__   :    Any				=			LMSDiscreteScheduler.from_pretrained(
				    '''ssube/stable-diffusion-x4-upscaler-onnx'''			,subfolder='''scheduler'''						)
				lowercase__   :    List[str]				=			OnnxStableDiffusionUpscalePipeline.from_pretrained(
				    '''ssube/stable-diffusion-x4-upscaler-onnx'''			,scheduler=_snake_case			,provider=self.gpu_provider			,sess_options=self.gpu_options			,)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    List[Any]				=			'''A fantasy landscape, trending on artstation'''

				lowercase__   :    Optional[int]				=			torch.manual_seed(0						)
				lowercase__   :    Union[str, Any]				=			pipe(
				    prompt=_snake_case			,image=_snake_case			,guidance_scale=7.5			,num_inference_steps=20			,generator=_snake_case			,output_type='''np'''			,)
				lowercase__   :    List[str]				=			output.images
				lowercase__   :    str				=			images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 512, 3)
				lowercase__   :    str				=			np.array(
				    [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566]						)
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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





"""simple docstring"""







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        __A       (	datasets.Metric    ):







		'''simple docstring'''





		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		str:






				"""simple docstring"""



				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						:  str			,_snake_case						:  Dict						)					->		Dict:






				"""simple docstring"""



				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						:  Dict			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Tuple=0.9			,_snake_case						:  Optional[int]=3			,_snake_case						:  Union[str, Any]=0.5						)					->		List[str]:






				"""simple docstring"""



				if NLTK_VERSION >= version.Version('''3.6.5'''						):
						lowercase__   :    int				=			[
						    meteor_score.single_meteor_score(
						        word_tokenize(_snake_case						)			,word_tokenize(_snake_case						)			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]
				else:
						lowercase__   :    Tuple				=			[
						    meteor_score.single_meteor_score(_snake_case			,_snake_case			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]

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