
import gc
import random
import unittest

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

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
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

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







def 						_snake_case(  SCREAMING_SNAKE_CASE__				) ->    List[str]:
       lowercase							:     Optional[int]       	=      [tensor.shape for tensor in tensor_list]
       return all(shape == shapes[0] for shape in shapes[1:]				)

class __snake_case		(      __snake_case					,	__snake_case					,	__snake_case					,	unittest.TestCase     ):
    _a		:						List[str]=				StableDiffusionLatentUpscalePipeline
    _a		:						Optional[Any]=				TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
        "height",
        "width",
        "cross_attention_kwargs",
        "negative_prompt_embeds",
        "prompt_embeds",
    }
    _a		:						Dict=				PipelineTesterMixin.required_optional_params - {"num_images_per_prompt"}
    _a		:						Optional[int]=				TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
    _a		:						List[Any]=				frozenset(
        []     )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    _a		:						Dict=				frozenset([]     )

    _a		:						List[Any]=				True
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Any       	=      1
           lowercase							:     Optional[int]       	=      4
           lowercase							:     str       	=      (16, 16)

           lowercase							:     str       	=      floats_tensor((batch_size, num_channels) + sizes		,rng=random.Random(0      )      ).to(snake_case      )
           return image
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           torch.manual_seed(0      )
           lowercase							:     List[str]       	=      UNetaDConditionModel(
               act_fn="""gelu"""		,attention_head_dim=8		,norm_num_groups=snake_case		,block_out_channels=[32, 32, 64, 64]		,time_cond_proj_dim=160		,conv_in_kernel=1		,conv_out_kernel=1		,cross_attention_dim=32		,down_block_types=(
                   """KDownBlock2D""",
                   """KCrossAttnDownBlock2D""",
                   """KCrossAttnDownBlock2D""",
                   """KCrossAttnDownBlock2D""",
               )		,in_channels=8		,mid_block_type=snake_case		,only_cross_attention=snake_case		,out_channels=5		,resnet_time_scale_shift="""scale_shift"""		,time_embedding_type="""fourier"""		,timestep_post_act="""gelu"""		,up_block_types=("""KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KUpBlock2D""")		,)
           lowercase							:     List[str]       	=      AutoencoderKL(
               block_out_channels=[32, 32, 64, 64]		,in_channels=3		,out_channels=3		,down_block_types=[
                   """DownEncoderBlock2D""",
                   """DownEncoderBlock2D""",
                   """DownEncoderBlock2D""",
                   """DownEncoderBlock2D""",
               ]		,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D"""]		,latent_channels=4		,)
           lowercase							:     Optional[int]       	=      EulerDiscreteScheduler(prediction_type="""sample"""      )
           lowercase							:     Optional[int]       	=      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=1000		,hidden_act="""quick_gelu"""		,projection_dim=512		,)
           lowercase							:     List[str]       	=      CLIPTextModel(snake_case      )
           lowercase							:     Union[str, Any]       	=      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      )

           lowercase							:     str       	=      {
               '''unet''': model.eval(),
               '''vae''': vae.eval(),
               '''scheduler''': scheduler,
               '''text_encoder''': text_encoder,
               '''tokenizer''': tokenizer,
           }

           return components
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=0      ):



           '''simple docstring'''







           if str(snake_case      ).startswith("""mps"""      ):
                  lowercase							:     List[Any]       	=      torch.manual_seed(snake_case      )
           else:
                  lowercase							:     Optional[Any]       	=      torch.Generator(device=snake_case      ).manual_seed(snake_case      )
           lowercase							:     List[str]       	=      {
               '''prompt''': '''A painting of a squirrel eating a burger''',
               '''image''': self.dummy_image.cpu(),
               '''generator''': generator,
               '''num_inference_steps''': 2,
               '''output_type''': '''numpy''',
           }
           return inputs
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      '''cpu'''

           lowercase							:     str       	=      self.get_dummy_components()
           lowercase							:     List[Any]       	=      self.pipeline_class(**snake_case      )
           pipe.to(snake_case      )
           pipe.set_progress_bar_config(disable=snake_case      )

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

           self.assertEqual(image.shape		,(1, 256, 256, 3)      )
           lowercase							:     Union[str, Any]       	=      np.array(
               [0.47_222_412, 0.41_921_633, 0.44_717_434, 0.46_874_192, 0.42_588_258, 0.46_150_726, 0.4_677_534, 0.45_583_832, 0.48_579_055]      )
           lowercase							:     int       	=      np.abs(image_slice.flatten() - expected_slice      ).max()
           self.assertLessEqual(snake_case		,1e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_attention_slicing_forward_pass(expected_max_diff=7e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_cpu_offload_forward_pass(expected_max_diff=3e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_inference_batch_single_identical(expected_max_diff=7e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_save_load_local(expected_max_difference=3e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_save_load_optional_components(expected_max_difference=3e-3      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      [
               '''DDIMScheduler''',
               '''DDPMScheduler''',
               '''PNDMScheduler''',
               '''HeunDiscreteScheduler''',
               '''EulerAncestralDiscreteScheduler''',
               '''KDPM2DiscreteScheduler''',
               '''KDPM2AncestralDiscreteScheduler''',
               '''DPMSolverSDEScheduler''',
           ]
           lowercase							:     List[str]       	=      self.get_dummy_components()
           lowercase							:     List[Any]       	=      self.pipeline_class(**snake_case      )

           # make sure that PNDM does not need warm-up
           pipe.scheduler.register_to_config(skip_prk_steps=snake_case      )

           pipe.to(snake_case      )
           pipe.set_progress_bar_config(disable=snake_case      )
           lowercase							:     Tuple       	=      self.get_dummy_inputs(snake_case      )
           lowercase							:     Tuple       	=      2

           lowercase							:     List[str]       	=      []
           for scheduler_enum in KarrasDiffusionSchedulers:
                  if scheduler_enum.name in skip_schedulers:
                         # no sigma schedulers are not supported
                         # no schedulers
                         continue

                  lowercase							:     Dict       	=      getattr(snake_case		,scheduler_enum.name      )
                  lowercase							:     int       	=      scheduler_cls.from_config(pipe.scheduler.config      )
                  lowercase							:     Optional[int]       	=      pipe(**snake_case      )[0]
                  outputs.append(snake_case      )

           assert check_same_shape(snake_case      )






@require_torch_gpu
@slow
class __snake_case		(      unittest.TestCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      torch.manual_seed(33      )

           lowercase							:     Any       	=      StableDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4"""		,torch_dtype=torch.floataa      )
           pipe.to("""cuda"""      )

           lowercase							:     str       	=      StableDiffusionLatentUpscalePipeline.from_pretrained(
               """stabilityai/sd-x2-latent-upscaler"""		,torch_dtype=torch.floataa      )
           upscaler.to("""cuda"""      )

           lowercase							:     List[str]       	=      '''a photo of an astronaut high resolution, unreal engine, ultra realistic'''

           lowercase							:     str       	=      pipe(snake_case		,generator=snake_case		,output_type="""latent"""      ).images

           lowercase							:     Union[str, Any]       	=      upscaler(
               prompt=snake_case		,image=snake_case		,num_inference_steps=20		,guidance_scale=0		,generator=snake_case		,output_type="""np"""		,).images[0]

           lowercase							:     List[str]       	=      load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy"""      )
           assert np.abs((expected_image - image).mean()      ) < 5e-2
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      torch.manual_seed(33      )

           lowercase							:     int       	=      StableDiffusionLatentUpscalePipeline.from_pretrained(
               """stabilityai/sd-x2-latent-upscaler"""		,torch_dtype=torch.floataa      )
           upscaler.to("""cuda"""      )

           lowercase							:     List[str]       	=      '''the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas'''

           lowercase							:     Tuple       	=      load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png"""      )

           lowercase							:     Optional[int]       	=      upscaler(
               prompt=snake_case		,image=snake_case		,num_inference_steps=20		,guidance_scale=0		,generator=snake_case		,output_type="""np"""		,).images[0]

           lowercase							:     List[str]       	=      load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy"""      )
           assert np.abs((expected_image - image).max()      ) < 5e-2


'''simple docstring'''




from scipy.stats import pearsonr

import datasets


lowercase			:				Optional[int]    		=			'\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n'


lowercase			:				Optional[Any]    		=			'\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        [\'p-value\', \'pearsonr\']\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n        >>> print(round(results[\'p-value\'], 2))\n        0.15\n'


lowercase			:				str    		=			'\n@article{2020SciPy-NMeth,\nauthor  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n      Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n      Kern, Robert and Larson, Eric and Carey, C J and\n      Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n      Harris, Charles R. and Archibald, Anne M. and\n      Ribeiro, Antonio H. and Pedregosa, Fabian and\n      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n      Computing in Python}},\njournal = {Nature Methods},\nyear    = {2020},\nvolume  = {17},\npages   = {261--272},\nadsurl  = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n'





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





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         return datasets.MetricInfo(
             description=_DESCRIPTION						,			citation=_CITATION						,			inputs_description=_KWARGS_DESCRIPTION						,			features=datasets.Features(
                 {
                     '''predictions''': datasets.Value('''float'''	),
                     '''references''': datasets.Value('''float'''	),
                 }	)						,			reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']						,			)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=False	) ->				Union[str, Any]:






         """simple docstring"""






         if return_pvalue:
             A       :   Union[str, Any]					=						pearsonr(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             return {"pearsonr": results[0], "p-value": results[1]}
         else:
             return {"pearsonr": float(pearsonr(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)[0]	)}




