



"""simple docstring"""


from scipy.stats import spearmanr

import datasets


snake_case_    					=	"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

snake_case_    					=	"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

snake_case_    					=	R"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""







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



						"""simple docstring"""






						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      List[str]:
												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.spearmanr.html']       ,  )






						def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:Union[str, Any]       ,  lowercase_			:Optional[int]       ,  lowercase_			:int=False )    ->      Any:
												UpperCAmelCase					=			spearmanr(lowercase_       ,  lowercase_ )
												if return_pvalue:
																		return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
												else:
																		return {"spearmanr": results[0]}










"""simple docstring"""


from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


snake_case_    					=	logging.get_logger(__name__)  # pylint: disable=invalid-name







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""






						def __init__( self			:Optional[Any]       ,  lowercase_			:CLIPSegForImageSegmentation       ,  lowercase_			:CLIPSegProcessor       ,  lowercase_			:AutoencoderKL       ,  lowercase_			:CLIPTextModel       ,  lowercase_			:CLIPTokenizer       ,  lowercase_			:UNetaDConditionModel       ,  lowercase_			:Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       ,  lowercase_			:StableDiffusionSafetyChecker       ,  lowercase_			:CLIPImageProcessor       ,  )    ->      List[str]:
												super().__init__()

												if hasattr(scheduler.config       ,  'steps_offset' ) and scheduler.config.steps_offset != 1:
																		UpperCAmelCase					=			(
																		    f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"""
																		    f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """
																		    'to update the config accordingly as leaving `steps_offset` might led to incorrect results'
																		    ' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'
																		    ' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'
																		    ' file'
																		)
																		deprecate('steps_offset!=1'       ,  '1.0.0'       ,  lowercase_       ,  standard_warn=lowercase_ )
																		UpperCAmelCase					=			dict(scheduler.config )
																		UpperCAmelCase					=			1
																		UpperCAmelCase					=			FrozenDict(lowercase_ )

												if hasattr(scheduler.config       ,  'skip_prk_steps' ) and scheduler.config.skip_prk_steps is False:
																		UpperCAmelCase					=			(
																		    f"""The configuration file of this scheduler: {scheduler} has not set the configuration"""
																		    ' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make'
																		    ' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to'
																		    ' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face'
																		    ' Hub, it would be very nice if you could open a Pull request for the'
																		    ' `scheduler/scheduler_config.json` file'
																		)
																		deprecate('skip_prk_steps not set'       ,  '1.0.0'       ,  lowercase_       ,  standard_warn=lowercase_ )
																		UpperCAmelCase					=			dict(scheduler.config )
																		UpperCAmelCase					=			True
																		UpperCAmelCase					=			FrozenDict(lowercase_ )

												if safety_checker is None:
																		logger.warning(
																		    f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
																		    ' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'
																		    ' results in services or applications open to the public. Both the diffusers team and Hugging Face'
																		    ' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'
																		    ' it only for use-cases that involve analyzing network behavior or auditing its results. For more'
																		    ' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .' )

												self.register_modules(
												    segmentation_model=lowercase_       ,  segmentation_processor=lowercase_       ,  vae=lowercase_       ,  text_encoder=lowercase_       ,  tokenizer=lowercase_       ,  unet=lowercase_       ,  scheduler=lowercase_       ,  safety_checker=lowercase_       ,  feature_extractor=lowercase_       ,  )






						def      UpperCAmelCase__					( self			:Optional[int]       ,  lowercase_			:Optional[Union[str, int]] = "auto" )    ->      int:
												if slice_size == "auto":
																		# half the attention head size is usually a good trade-off between
																		# speed and memory
																		UpperCAmelCase					=			self.unet.config.attention_head_dim // 2
												self.unet.set_attention_slice(lowercase_ )






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      List[str]:
												self.enable_attention_slicing(lowercase_ )






						def      UpperCAmelCase__					( self			:int )    ->      int:
												if is_accelerate_available():
																		from accelerate import cpu_offload
												else:
																		raise ImportError('Please install accelerate via `pip install accelerate`' )

												UpperCAmelCase					=			torch.device('cuda' )

												for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
																		if cpu_offloaded_model is not None:
																								cpu_offload(lowercase_       ,  lowercase_ )






						@property
						# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      List[str]:
												if self.device != torch.device('meta' ) or not hasattr(self.unet       ,  '_hf_hook' ):
																		return self.device
												for module in self.unet.modules():
																		if (
																		    hasattr(lowercase_       ,  '_hf_hook' )
																		    and hasattr(module._hf_hook       ,  'execution_device' )
																		    and module._hf_hook.execution_device is not None
																		):
																								return torch.device(module._hf_hook.execution_device )
												return self.device






						@torch.no_grad()
						def __call__( self			:Optional[Any]       ,  lowercase_			:Union[str, List[str]]       ,  lowercase_			:Union[torch.FloatTensor, PIL.Image.Image]       ,  lowercase_			:str       ,  lowercase_			:int = 5_12       ,  lowercase_			:int = 5_12       ,  lowercase_			:int = 50       ,  lowercase_			:float = 7.5       ,  lowercase_			:Optional[Union[str, List[str]]] = None       ,  lowercase_			:Optional[int] = 1       ,  lowercase_			:float = 0.0       ,  lowercase_			:Optional[torch.Generator] = None       ,  lowercase_			:Optional[torch.FloatTensor] = None       ,  lowercase_			:Optional[str] = "pil"       ,  lowercase_			:bool = True       ,  lowercase_			:Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,  lowercase_			:int = 1       ,  **lowercase_			:int       ,  )    ->      int:
												UpperCAmelCase					=			self.segmentation_processor(
												    text=[text]       ,  images=[image]       ,  padding='max_length'       ,  return_tensors='pt' ).to(self.device )
												UpperCAmelCase					=			self.segmentation_model(**lowercase_ )
												UpperCAmelCase					=			torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy()
												UpperCAmelCase					=			self.numpy_to_pil(lowercase_ )[0].resize(image.size )

												# Run inpainting pipeline with the generated mask
												UpperCAmelCase					=			StableDiffusionInpaintPipeline(
												    vae=self.vae       ,  text_encoder=self.text_encoder       ,  tokenizer=self.tokenizer       ,  unet=self.unet       ,  scheduler=self.scheduler       ,  safety_checker=self.safety_checker       ,  feature_extractor=self.feature_extractor       ,  )
												return inpainting_pipeline(
												    prompt=lowercase_       ,  image=lowercase_       ,  mask_image=lowercase_       ,  height=lowercase_       ,  width=lowercase_       ,  num_inference_steps=lowercase_       ,  guidance_scale=lowercase_       ,  negative_prompt=lowercase_       ,  num_images_per_prompt=lowercase_       ,  eta=lowercase_       ,  generator=lowercase_       ,  latents=lowercase_       ,  output_type=lowercase_       ,  return_dict=lowercase_       ,  callback=lowercase_       ,  callback_steps=lowercase_       ,  )





