



"""simple docstring"""




from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .text_encoder import MultilingualCLIP


_UpperCamelCase: List[Any]										=     logging.get_logger(__name__)  # pylint: disable=invalid-name

_UpperCamelCase: Optional[int]										=     '\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> negative_image_emb = out.negative_image_embeds\n\n        >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n        >>> pipe.to("cuda")\n\n        >>> image = pipe(\n        ...     prompt,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=negative_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ... ).images\n\n        >>> image[0].save("cat.png")\n        ```\n'


def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase=8 )   ->	Union[str, Any]:






      '''simple docstring'''


      lowercase     :					Any 		=      h // scale_factor**2
      if h % scale_factor**2 != 0:
            new_h += 1
      lowercase     :					Tuple 		=      w // scale_factor**2
      if w % scale_factor**2 != 0:
            new_w += 1
      return new_h * scale_factor, new_w * scale_factor





class      a__						(  A__   ):


   def __init__(							self					:							Any,   lowerCAmelCase					:							Optional[Any],   lowerCAmelCase					:							List[Any],   lowerCAmelCase					:							int,   lowerCAmelCase					:							Optional[Any],   lowerCAmelCase					:							str,   )			->				str:
         super().__init__()

         self.register_modules(
             text_encoder=UpperCamelCase_,   tokenizer=UpperCamelCase_,   unet=UpperCamelCase_,   scheduler=UpperCamelCase_,   movq=UpperCamelCase_,   )
         lowercase     :					Union[str, Any] 		=      2 ** (len(self.movq.config.block_out_channels	) - 1)


   def 				lowercase (							self					:							List[Any],   lowerCAmelCase					:							Optional[Any],   lowerCAmelCase					:							Optional[int],   lowerCAmelCase					:							str,   lowerCAmelCase					:							List[str],   lowerCAmelCase					:							Dict,   lowerCAmelCase					:							str	)			->				str:


         if latents is None:
               lowercase     :					str 		=      randn_tensor(UpperCamelCase_,   generator=UpperCamelCase_,   device=UpperCamelCase_,   dtype=UpperCamelCase_	)
         else:
               if latents.shape != shape:
                     raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''	)
               lowercase     :					Dict 		=      latents.to(UpperCamelCase_	)

         lowercase     :					Any 		=      latents * scheduler.init_noise_sigma
         return latents


   def 				lowercase (							self					:							str,   lowerCAmelCase					:							str,   lowerCAmelCase					:							List[str],   lowerCAmelCase					:							int,   lowerCAmelCase					:							List[str],   lowerCAmelCase					:							str=None,   )			->				List[Any]:
         lowercase     :					List[Any] 		=      len(UpperCamelCase_	) if isinstance(UpperCamelCase_,   UpperCamelCase_	) else 1
         # get prompt text embeddings
         lowercase     :					List[str] 		=      self.tokenizer(
             UpperCamelCase_,   padding='max_length',   truncation=UpperCamelCase_,   max_length=77,   return_attention_mask=UpperCamelCase_,   add_special_tokens=UpperCamelCase_,   return_tensors='pt',   )

         lowercase     :					str 		=      text_inputs.input_ids
         lowercase     :					List[str] 		=      self.tokenizer(UpperCamelCase_,   padding='longest',   return_tensors='pt'	).input_ids

         if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCamelCase_,   UpperCamelCase_	):
               lowercase     :					Tuple 		=      self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]	)
               logger.warning(
                   'The following part of your input was truncated because CLIP can only handle sequences up to'
                   f''' {self.tokenizer.model_max_length} tokens: {removed_text}'''	)

         lowercase     :					Union[str, Any] 		=      text_input_ids.to(UpperCamelCase_	)
         lowercase     :					Optional[int] 		=      text_inputs.attention_mask.to(UpperCamelCase_	)

         lowercase     :					Optional[int] 		=      self.text_encoder(
             input_ids=UpperCamelCase_,   attention_mask=UpperCamelCase_	)

         lowercase     :					Tuple 		=      prompt_embeds.repeat_interleave(UpperCamelCase_,   dim=0	)
         lowercase     :					List[Any] 		=      text_encoder_hidden_states.repeat_interleave(UpperCamelCase_,   dim=0	)
         lowercase     :					str 		=      text_mask.repeat_interleave(UpperCamelCase_,   dim=0	)

         if do_classifier_free_guidance:
               lowercase     :					List[str]
               if negative_prompt is None:
                     lowercase     :					Dict 		=      [''''''] * batch_size
               elif type(UpperCamelCase_	) is not type(UpperCamelCase_	):
                     raise TypeError(
                         f'''`negative_prompt` should be the same type to `prompt`, but got {type(UpperCamelCase_	)} !='''
                         f''' {type(UpperCamelCase_	)}.'''	)
               elif isinstance(UpperCamelCase_,   UpperCamelCase_	):
                     lowercase     :					List[str] 		=      [negative_prompt]
               elif batch_size != len(UpperCamelCase_	):
                     raise ValueError(
                         f'''`negative_prompt`: {negative_prompt} has batch size {len(UpperCamelCase_	)}, but `prompt`:'''
                         f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
                         ' the batch size of `prompt`.'	)
               else:
                     lowercase     :					Tuple 		=      negative_prompt

               lowercase     :					int 		=      self.tokenizer(
                   UpperCamelCase_,   padding='max_length',   max_length=77,   truncation=UpperCamelCase_,   return_attention_mask=UpperCamelCase_,   add_special_tokens=UpperCamelCase_,   return_tensors='pt',   )
               lowercase     :					List[str] 		=      uncond_input.input_ids.to(UpperCamelCase_	)
               lowercase     :					Union[str, Any] 		=      uncond_input.attention_mask.to(UpperCamelCase_	)

               lowercase     :					Optional[Any] 		=      self.text_encoder(
                   input_ids=UpperCamelCase_,   attention_mask=UpperCamelCase_	)

               # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

               lowercase     :					Optional[int] 		=      negative_prompt_embeds.shape[1]
               lowercase     :					List[Any] 		=      negative_prompt_embeds.repeat(1,   UpperCamelCase_	)
               lowercase     :					Any 		=      negative_prompt_embeds.view(batch_size * num_images_per_prompt,   UpperCamelCase_	)

               lowercase     :					List[str] 		=      uncond_text_encoder_hidden_states.shape[1]
               lowercase     :					Tuple 		=      uncond_text_encoder_hidden_states.repeat(1,   UpperCamelCase_,   1	)
               lowercase     :					List[str] 		=      uncond_text_encoder_hidden_states.view(
                   batch_size * num_images_per_prompt,   UpperCamelCase_,   -1	)
               lowercase     :					List[Any] 		=      uncond_text_mask.repeat_interleave(UpperCamelCase_,   dim=0	)

               # done duplicates

               # For classifier free guidance, we need to do two forward passes.
               # Here we concatenate the unconditional and text embeddings into a single batch
               # to avoid doing two forward passes
               lowercase     :					Tuple 		=      torch.cat([negative_prompt_embeds, prompt_embeds]	)
               lowercase     :					Optional[int] 		=      torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]	)

               lowercase     :					int 		=      torch.cat([uncond_text_mask, text_mask]	)

         return prompt_embeds, text_encoder_hidden_states, text_mask


   def 				lowercase (							self					:							Any,   lowerCAmelCase					:							Optional[Any]=0	)			->				Any:


         if is_accelerate_available():
               from accelerate import cpu_offload
         else:
               raise ImportError('Please install accelerate via `pip install accelerate`'	)

         lowercase     :					int 		=      torch.device(f'''cuda:{gpu_id}'''	)

         lowercase     :					Tuple 		=      [
             self.unet,
             self.text_encoder,
             self.movq,
         ]
         for cpu_offloaded_model in models:
               if cpu_offloaded_model is not None:
                     cpu_offload(UpperCamelCase_,   UpperCamelCase_	)


   def 				lowercase (							self					:							Optional[int],   lowerCAmelCase					:							Tuple=0	)			->				Dict:


         if is_accelerate_available() and is_accelerate_version('>=',   '0.17.0.dev0'	):
               from accelerate import cpu_offload_with_hook
         else:
               raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'	)

         lowercase     :					Tuple 		=      torch.device(f'''cuda:{gpu_id}'''	)

         if self.device.type != "cpu":
               self.to('cpu',   silence_dtype_warnings=UpperCamelCase_	)
               torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

         lowercase     :					str 		=      None
         for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
               lowercase     :					Union[str, Any] 		=      cpu_offload_with_hook(UpperCamelCase_,   UpperCamelCase_,   prev_module_hook=UpperCamelCase_	)

         if self.safety_checker is not None:
               lowercase     :					Optional[Any] 		=      cpu_offload_with_hook(self.safety_checker,   UpperCamelCase_,   prev_module_hook=UpperCamelCase_	)

         # We'll offload the last model manually.
         lowercase     :					Optional[Any] 		=      hook


   @property
   # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
   def 				lowercase (							self					:							List[Any]	)			->				Tuple:


         if not hasattr(self.unet,   '_hf_hook'	):
               return self.device
         for module in self.unet.modules():
               if (
                   hasattr(UpperCamelCase_,   '_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()
   @replace_example_docstring(UpperCamelCase_	)
   def __call__(							self					:							Any,   lowerCAmelCase					:							str,   lowerCAmelCase					:							Any,   lowerCAmelCase					:							str,   lowerCAmelCase					:							Optional[Any] = None,   lowerCAmelCase					:							Tuple = 512,   lowerCAmelCase					:							Tuple = 512,   lowerCAmelCase					:							Union[str, Any] = 100,   lowerCAmelCase					:							Optional[Any] = 4.0,   lowerCAmelCase					:							int = 1,   lowerCAmelCase					:							Any = None,   lowerCAmelCase					:							List[str] = None,   lowerCAmelCase					:							int = "pil",   lowerCAmelCase					:							Dict = True,   )			->				str:


         if isinstance(UpperCamelCase_,   UpperCamelCase_	):
               lowercase     :					int 		=      1
         elif isinstance(UpperCamelCase_,   UpperCamelCase_	):
               lowercase     :					Optional[int] 		=      len(UpperCamelCase_	)
         else:
               raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase_	)}'''	)

         lowercase     :					Optional[int] 		=      self._execution_device

         lowercase     :					Any 		=      batch_size * num_images_per_prompt
         lowercase     :					List[Any] 		=      guidance_scale > 1.0

         lowercase     :					Optional[Any] 		=      self._encode_prompt(
             UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_	)

         if isinstance(UpperCamelCase_,   UpperCamelCase_	):
               lowercase     :					Optional[Any] 		=      torch.cat(UpperCamelCase_,   dim=0	)
         if isinstance(UpperCamelCase_,   UpperCamelCase_	):
               lowercase     :					Optional[int] 		=      torch.cat(UpperCamelCase_,   dim=0	)

         if do_classifier_free_guidance:
               lowercase     :					int 		=      image_embeds.repeat_interleave(UpperCamelCase_,   dim=0	)
               lowercase     :					List[Any] 		=      negative_image_embeds.repeat_interleave(UpperCamelCase_,   dim=0	)

         lowercase     :					List[str] 		=      torch.cat([negative_image_embeds, image_embeds],   dim=0	).to(
             dtype=prompt_embeds.dtype,   device=UpperCamelCase_	)

         self.scheduler.set_timesteps(UpperCamelCase_,   device=UpperCamelCase_	)
         lowercase     :					int 		=      self.scheduler.timesteps

         lowercase     :					List[Any] 		=      self.unet.config.in_channels

         lowercase     :					Dict 		=      get_new_h_w(UpperCamelCase_,   UpperCamelCase_,   self.movq_scale_factor	)

         # create initial latent
         lowercase     :					List[Any] 		=      self.prepare_latents(
             (batch_size, num_channels_latents, height, width),   text_encoder_hidden_states.dtype,   UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_,   self.scheduler,   )

         for i, t in enumerate(self.progress_bar(UpperCamelCase_	)	):
               # expand the latents if we are doing classifier free guidance
               lowercase     :					List[Any] 		=      torch.cat([latents] * 2	) if do_classifier_free_guidance else latents

               lowercase     :					Any 		=      {'''text_embeds''': prompt_embeds, '''image_embeds''': image_embeds}
               lowercase     :					Optional[int] 		=      self.unet(
                   sample=UpperCamelCase_,   timestep=UpperCamelCase_,   encoder_hidden_states=UpperCamelCase_,   added_cond_kwargs=UpperCamelCase_,   return_dict=UpperCamelCase_,   )[0]

               if do_classifier_free_guidance:
                     lowercase     :					Optional[Any] 		=      noise_pred.split(latents.shape[1],   dim=1	)
                     lowercase     :					List[Any] 		=      noise_pred.chunk(2	)
                     lowercase     :					Optional[int] 		=      variance_pred.chunk(2	)
                     lowercase     :					int 		=      noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                     lowercase     :					Union[str, Any] 		=      torch.cat([noise_pred, variance_pred_text],   dim=1	)

               if not (
                   hasattr(self.scheduler.config,   'variance_type'	)
                   and self.scheduler.config.variance_type in ["learned", "learned_range"]
               ):
                     lowercase     :					int 		=      noise_pred.split(latents.shape[1],   dim=1	)

               # compute the previous noisy sample x_t -> x_t-1
               lowercase     :					Optional[int] 		=      self.scheduler.step(
                   UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_,   generator=UpperCamelCase_,   ).prev_sample
         # post-processing
         lowercase     :					List[Any] 		=      self.movq.decode(UpperCamelCase_,   force_not_quantize=UpperCamelCase_	)['''sample''']

         if output_type not in ["pt", "np", "pil"]:
               raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''	)

         if output_type in ["np", "pil"]:
               lowercase     :					List[str] 		=      image * 0.5 + 0.5
               lowercase     :					Optional[Any] 		=      image.clamp(0,   1	)
               lowercase     :					List[str] 		=      image.cpu().permute(0,   2,   3,   1	).float().numpy()

         if output_type == "pil":
               lowercase     :					str 		=      self.numpy_to_pil(UpperCamelCase_	)

         if not return_dict:
               return (image,)

         return ImagePipelineOutput(images=UpperCamelCase_	)




'''simple docstring'''
from scipy.stats import pearsonr

import datasets


__snake_case							      =     '''
Pearson correlation coefficient and p-value for testing non-correlation.
The 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.
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.
'''


__snake_case							      =     '''
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    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.
    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.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        [\'p-value\', \'pearsonr\']
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74
        >>> print(round(results[\'p-value\'], 2))
        0.15
'''


__snake_case							      =     '''
@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, Ilhan 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, Antonio 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    lowercase	(							datasets.Metric					):

		"""simple docstring"""

		def     lowerCAmelCase__				(		self							):

							'''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    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_=False							):

							'''simple docstring'''


							if return_pvalue:
												UpperCamelCase__   :Any												= pearsonr(UpperCamelCase_    ,   UpperCamelCase_							)
												return {"pearsonr": results[0], "p-value": results[1]}
							else:
												return {"pearsonr": float(pearsonr(UpperCamelCase_    ,   UpperCamelCase_							)[0]							)}