






'''simple docstring'''




import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput

class      lowerCamelCase_     (nn.Module   ):
      '''simple docstring'''

      def __init__(	self						:    List[str]						, A						:    int						, A						:    Tuple=1.0	):
             super().__init__()

             _UpperCAmelCase					:  Any											=   cut_size
             _UpperCAmelCase					:  Optional[int]											=   cut_power





      def 					_A     (	self						:    Tuple						, A						:    Dict						, A						:    List[str]	):
             _UpperCAmelCase				,  _UpperCAmelCase					:  str											=   pixel_values.shape[2:4]
             _UpperCAmelCase					:  List[Any]											=   min(__UpperCamelCase						, __UpperCamelCase	)
             _UpperCAmelCase					:  Tuple											=   min(__UpperCamelCase						, __UpperCamelCase						, self.cut_size	)
             _UpperCAmelCase					:  Optional[int]											=   []
             for _ in range(__UpperCamelCase	):
                    _UpperCAmelCase					:  Dict											=   int(torch.rand([]	) ** self.cut_power * (max_size - min_size) + min_size	)
                    _UpperCAmelCase					:  Union[str, Any]											=   torch.randint(0						, sideX - size + 1						, ()	)
                    _UpperCAmelCase					:  Optional[Any]											=   torch.randint(0						, sideY - size + 1						, ()	)
                    _UpperCAmelCase					:  Optional[Any]											=   pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
                    cutouts.append(F.adaptive_avg_poolad(__UpperCamelCase						, self.cut_size	)	)
             return torch.cat(__UpperCamelCase	)

def      UpperCamelCase_							( _UpperCAmelCase  :				Optional[int]      ,     _UpperCAmelCase  :				Tuple   )   ->   Any:


       """simple docstring"""







       _UpperCAmelCase					:  List[str]											=   F.normalize(_UpperCAmelCase      ,     dim=-1   )
       _UpperCAmelCase					:  List[Any]											=   F.normalize(_UpperCAmelCase      ,     dim=-1   )
       return (x - y).norm(dim=-1   ).div(2   ).arcsin().pow(2   ).mul(2   )

def      UpperCamelCase_							( _UpperCAmelCase  :				List[str]      ,     _UpperCAmelCase  :				Union[str, Any]   )   ->   Union[str, Any]:


       """simple docstring"""







       for param in model.parameters():
              _UpperCAmelCase					:  Optional[int]											=   value


class      lowerCamelCase_     (lowercase_   ):
      '''simple docstring'''

      def __init__(	self						:    List[str]						, A						:    AutoencoderKL						, A						:    CLIPTextModel						, A						:    CLIPModel						, A						:    CLIPTokenizer						, A						:    UNetaDConditionModel						, A						:    Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler]						, A						:    CLIPImageProcessor						, ):
             super().__init__()
             self.register_modules(
                 vae=__UpperCamelCase						, text_encoder=__UpperCamelCase						, clip_model=__UpperCamelCase						, tokenizer=__UpperCamelCase						, unet=__UpperCamelCase						, scheduler=__UpperCamelCase						, feature_extractor=__UpperCamelCase						, )

             _UpperCAmelCase					:  Dict											=   transforms.Normalize(mean=feature_extractor.image_mean						, std=feature_extractor.image_std	)
             _UpperCAmelCase					:  Union[str, Any]											=   (
                 feature_extractor.size
                 if isinstance(feature_extractor.size						, __UpperCamelCase	)
                 else feature_extractor.size["shortest_edge"]
             )
             _UpperCAmelCase					:  Dict											=   MakeCutouts(self.cut_out_size	)

             set_requires_grad(self.text_encoder						, __UpperCamelCase	)
             set_requires_grad(self.clip_model						, __UpperCamelCase	)




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




      def 					_A     (	self						:    Optional[Any]	):
             self.enable_attention_slicing(__UpperCamelCase	)




      def 					_A     (	self						:    str	):
             set_requires_grad(self.vae						, __UpperCamelCase	)




      def 					_A     (	self						:    Optional[int]	):
             set_requires_grad(self.vae						, __UpperCamelCase	)




      def 					_A     (	self						:    str	):
             set_requires_grad(self.unet						, __UpperCamelCase	)




      def 					_A     (	self						:    str	):
             set_requires_grad(self.unet						, __UpperCamelCase	)




      @torch.enable_grad()
      def 					_A     (	self						:    Optional[int]						, A						:    str						, A						:    str						, A						:    Any						, A						:    str						, A						:    Optional[int]						, A						:    List[Any]						, A						:    Optional[Any]						, A						:    int						, A						:    List[str]=True						, ):
             _UpperCAmelCase					:  str											=   latents.detach().requires_grad_()

             _UpperCAmelCase					:  List[Any]											=   self.scheduler.scale_model_input(__UpperCamelCase						, __UpperCamelCase	)

             # predict the noise residual
             _UpperCAmelCase					:  str											=   self.unet(__UpperCamelCase						, __UpperCamelCase						, encoder_hidden_states=__UpperCamelCase	).sample

             if isinstance(self.scheduler						, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)	):
                    _UpperCAmelCase					:  int											=   self.scheduler.alphas_cumprod[timestep]
                    _UpperCAmelCase					:  Union[str, Any]											=   1 - alpha_prod_t
                    # compute predicted original sample from predicted noise also called
                    # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
                    _UpperCAmelCase					:  Tuple											=   (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

                    _UpperCAmelCase					:  Optional[int]											=   torch.sqrt(__UpperCamelCase	)
                    _UpperCAmelCase					:  Optional[int]											=   pred_original_sample * (fac) + latents * (1 - fac)
             elif isinstance(self.scheduler						, __UpperCamelCase	):
                    _UpperCAmelCase					:  str											=   self.scheduler.sigmas[index]
                    _UpperCAmelCase					:  Tuple											=   latents - sigma * noise_pred
             else:
                    raise ValueError(F"""scheduler type {type(self.scheduler	)} not supported"""	)

             _UpperCAmelCase					:  List[Any]											=   1 / self.vae.config.scaling_factor * sample
             _UpperCAmelCase					:  List[str]											=   self.vae.decode(__UpperCamelCase	).sample
             _UpperCAmelCase					:  int											=   (image / 2 + 0.5).clamp(0						, 1	)

             if use_cutouts:
                    _UpperCAmelCase					:  int											=   self.make_cutouts(__UpperCamelCase						, __UpperCamelCase	)
             else:
                    _UpperCAmelCase					:  List[str]											=   transforms.Resize(self.cut_out_size	)(__UpperCamelCase	)
             _UpperCAmelCase					:  Optional[Any]											=   self.normalize(__UpperCamelCase	).to(latents.dtype	)

             _UpperCAmelCase					:  List[Any]											=   self.clip_model.get_image_features(__UpperCamelCase	)
             _UpperCAmelCase					:  int											=   image_embeddings_clip / image_embeddings_clip.norm(p=2						, dim=-1						, keepdim=__UpperCamelCase	)

             if use_cutouts:
                    _UpperCAmelCase					:  str											=   spherical_dist_loss(__UpperCamelCase						, __UpperCamelCase	)
                    _UpperCAmelCase					:  Union[str, Any]											=   dists.view([num_cutouts, sample.shape[0], -1]	)
                    _UpperCAmelCase					:  Dict											=   dists.sum(2	).mean(0	).sum() * clip_guidance_scale
             else:
                    _UpperCAmelCase					:  Any											=   spherical_dist_loss(__UpperCamelCase						, __UpperCamelCase	).mean() * clip_guidance_scale

             _UpperCAmelCase					:  Dict											=   -torch.autograd.grad(__UpperCamelCase						, __UpperCamelCase	)[0]

             if isinstance(self.scheduler						, __UpperCamelCase	):
                    _UpperCAmelCase					:  int											=   latents.detach() + grads * (sigma**2)
                    _UpperCAmelCase					:  Any											=   noise_pred_original
             else:
                    _UpperCAmelCase					:  List[Any]											=   noise_pred_original - torch.sqrt(__UpperCamelCase	) * grads
             return noise_pred, latents





      @torch.no_grad()
      def __call__(	self						:    Any						, A						:    Union[str, List[str]]						, A						:    Optional[int] = 512						, A						:    Optional[int] = 512						, A						:    Optional[int] = 50						, A						:    Optional[float] = 7.5						, A						:    Optional[int] = 1						, A						:    float = 0.0						, A						:    Optional[float] = 100						, A						:    Optional[Union[str, List[str]]] = None						, A						:    Optional[int] = 4						, A						:    Optional[bool] = True						, A						:    Optional[torch.Generator] = None						, A						:    Optional[torch.FloatTensor] = None						, A						:    Optional[str] = "pil"						, A						:    bool = True						, ):
             if isinstance(__UpperCamelCase						, __UpperCamelCase	):
                    _UpperCAmelCase					:  Tuple											=   1
             elif isinstance(__UpperCamelCase						, __UpperCamelCase	):
                    _UpperCAmelCase					:  List[str]											=   len(__UpperCamelCase	)
             else:
                    raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(__UpperCamelCase	)}"""	)

             if height % 8 != 0 or width % 8 != 0:
                    raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""	)

             # get prompt text embeddings
             _UpperCAmelCase					:  str											=   self.tokenizer(
                 __UpperCamelCase						, padding="max_length"						, max_length=self.tokenizer.model_max_length						, truncation=__UpperCamelCase						, return_tensors="pt"						, )
             _UpperCAmelCase					:  int											=   self.text_encoder(text_input.input_ids.to(self.device	)	)[0]
             # duplicate text embeddings for each generation per prompt
             _UpperCAmelCase					:  str											=   text_embeddings.repeat_interleave(__UpperCamelCase						, dim=0	)

             if clip_guidance_scale > 0:
                    if clip_prompt is not None:
                           _UpperCAmelCase					:  Optional[int]											=   self.tokenizer(
                               __UpperCamelCase						, padding="max_length"						, max_length=self.tokenizer.model_max_length						, truncation=__UpperCamelCase						, return_tensors="pt"						, ).input_ids.to(self.device	)
                    else:
                           _UpperCAmelCase					:  Tuple											=   text_input.input_ids.to(self.device	)
                    _UpperCAmelCase					:  str											=   self.clip_model.get_text_features(__UpperCamelCase	)
                    _UpperCAmelCase					:  Optional[Any]											=   text_embeddings_clip / text_embeddings_clip.norm(p=2						, dim=-1						, keepdim=__UpperCamelCase	)
                    # duplicate text embeddings clip for each generation per prompt
                    _UpperCAmelCase					:  Optional[Any]											=   text_embeddings_clip.repeat_interleave(__UpperCamelCase						, dim=0	)

             # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
             # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
             # corresponds to doing no classifier free guidance.
             _UpperCAmelCase					:  Tuple											=   guidance_scale > 1.0
             # get unconditional embeddings for classifier free guidance
             if do_classifier_free_guidance:
                    _UpperCAmelCase					:  Union[str, Any]											=   text_input.input_ids.shape[-1]
                    _UpperCAmelCase					:  Optional[Any]											=   self.tokenizer([""]						, padding="max_length"						, max_length=__UpperCamelCase						, return_tensors="pt"	)
                    _UpperCAmelCase					:  List[str]											=   self.text_encoder(uncond_input.input_ids.to(self.device	)	)[0]
                    # duplicate unconditional embeddings for each generation per prompt
                    _UpperCAmelCase					:  List[Any]											=   uncond_embeddings.repeat_interleave(__UpperCamelCase						, dim=0	)

                    # 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
                    _UpperCAmelCase					:  Optional[int]											=   torch.cat([uncond_embeddings, text_embeddings]	)

             # get the initial random noise unless the user supplied it

             # Unlike in other pipelines, latents need to be generated in the target device
             # for 1-to-1 results reproducibility with the CompVis implementation.
             # However this currently doesn't work in `mps`.
             _UpperCAmelCase					:  List[Any]											=   (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
             _UpperCAmelCase					:  str											=   text_embeddings.dtype
             if latents is None:
                    if self.device.type == "mps":
                           # randn does not work reproducibly on mps
                           _UpperCAmelCase					:  str											=   torch.randn(__UpperCamelCase						, generator=__UpperCamelCase						, device="cpu"						, dtype=__UpperCamelCase	).to(
                               self.device	)
                    else:
                           _UpperCAmelCase					:  Tuple											=   torch.randn(__UpperCamelCase						, generator=__UpperCamelCase						, device=self.device						, dtype=__UpperCamelCase	)
             else:
                    if latents.shape != latents_shape:
                           raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""	)
                    _UpperCAmelCase					:  List[Any]											=   latents.to(self.device	)

             # set timesteps
             _UpperCAmelCase					:  List[Any]											=   "offset" in set(inspect.signature(self.scheduler.set_timesteps	).parameters.keys()	)
             _UpperCAmelCase					:  Union[str, Any]											=   {}
             if accepts_offset:
                    _UpperCAmelCase					:  Union[str, Any]											=   1

             self.scheduler.set_timesteps(__UpperCamelCase						, **__UpperCamelCase	)

             # Some schedulers like PNDM have timesteps as arrays
             # It's more optimized to move all timesteps to correct device beforehand
             _UpperCAmelCase					:  Union[str, Any]											=   self.scheduler.timesteps.to(self.device	)

             # scale the initial noise by the standard deviation required by the scheduler
             _UpperCAmelCase					:  Any											=   latents * self.scheduler.init_noise_sigma

             # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
             # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
             # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
             # and should be between [0, 1]
             _UpperCAmelCase					:  str											=   "eta" in set(inspect.signature(self.scheduler.step	).parameters.keys()	)
             _UpperCAmelCase					:  Optional[Any]											=   {}
             if accepts_eta:
                    _UpperCAmelCase					:  Any											=   eta

             # check if the scheduler accepts generator
             _UpperCAmelCase					:  Union[str, Any]											=   "generator" in set(inspect.signature(self.scheduler.step	).parameters.keys()	)
             if accepts_generator:
                    _UpperCAmelCase					:  List[str]											=   generator

             for i, t in enumerate(self.progress_bar(__UpperCamelCase	)	):
                    # expand the latents if we are doing classifier free guidance
                    _UpperCAmelCase					:  Tuple											=   torch.cat([latents] * 2	) if do_classifier_free_guidance else latents
                    _UpperCAmelCase					:  Optional[int]											=   self.scheduler.scale_model_input(__UpperCamelCase						, __UpperCamelCase	)

                    # predict the noise residual
                    _UpperCAmelCase					:  Tuple											=   self.unet(__UpperCamelCase						, __UpperCamelCase						, encoder_hidden_states=__UpperCamelCase	).sample

                    # perform classifier free guidance
                    if do_classifier_free_guidance:
                           _UpperCAmelCase				,  _UpperCAmelCase					:  Dict											=   noise_pred.chunk(2	)
                           _UpperCAmelCase					:  int											=   noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                    # perform clip guidance
                    if clip_guidance_scale > 0:
                           _UpperCAmelCase					:  List[str]											=   (
                               text_embeddings.chunk(2	)[1] if do_classifier_free_guidance else text_embeddings
                           )
                           _UpperCAmelCase				,  _UpperCAmelCase					:  Optional[Any]											=   self.cond_fn(
                               __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, )

                    # compute the previous noisy sample x_t -> x_t-1
                    _UpperCAmelCase					:  Optional[Any]											=   self.scheduler.step(__UpperCamelCase						, __UpperCamelCase						, __UpperCamelCase						, **__UpperCamelCase	).prev_sample

             # scale and decode the image latents with vae
             _UpperCAmelCase					:  Union[str, Any]											=   1 / self.vae.config.scaling_factor * latents
             _UpperCAmelCase					:  Optional[int]											=   self.vae.decode(__UpperCamelCase	).sample

             _UpperCAmelCase					:  Optional[Any]											=   (image / 2 + 0.5).clamp(0						, 1	)
             _UpperCAmelCase					:  Union[str, Any]											=   image.cpu().permute(0						, 2						, 3						, 1	).numpy()

             if output_type == "pil":
                    _UpperCAmelCase					:  Any											=   self.numpy_to_pil(__UpperCamelCase	)

             if not return_dict:
                    return (image, None)

             return StableDiffusionPipelineOutput(images=__UpperCamelCase						, nsfw_content_detected=__UpperCamelCase	)


'''simple docstring'''




from sklearn.metrics import accuracy_score

import datasets


__SCREAMING_SNAKE_CASE	:					Optional[int]					=  """
Accuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
 Where:
TP: True positive
TN: True negative
FP: False positive
FN: False negative
"""


__SCREAMING_SNAKE_CASE	:					Any					=  """
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.

Examples:

    Example 1-A simple example
        >>> accuracy_metric = datasets.load_metric(\"accuracy\")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])
        >>> print(results)
        {'accuracy': 0.5}

    Example 2-The same as Example 1, except with `normalize` set to `False`.
        >>> accuracy_metric = datasets.load_metric(\"accuracy\")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)
        >>> print(results)
        {'accuracy': 3.0}

    Example 3-The same as Example 1, except with `sample_weight` set.
        >>> accuracy_metric = datasets.load_metric(\"accuracy\")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])
        >>> print(results)
        {'accuracy': 0.8778625954198473}
"""


__SCREAMING_SNAKE_CASE	:					Optional[int]					=  """
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,			_KWARGS_DESCRIPTION   )
class      lowerCamelCase_     (datasets.Metric   ):
      '''simple docstring'''

      def 					_A     (	self						:    int	):
             return datasets.MetricInfo(
                 description=_DESCRIPTION						, citation=_CITATION						, inputs_description=_KWARGS_DESCRIPTION						, features=datasets.Features(
                     {
                         "predictions": datasets.Sequence(datasets.Value("int32"	)	),
                         "references": datasets.Sequence(datasets.Value("int32"	)	),
                     }
                     if self.config_name == "multilabel"
                     else {
                         "predictions": datasets.Value("int32"	),
                         "references": datasets.Value("int32"	),
                     }	)						, reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"]						, )





      def 					_A     (	self						:    str						, A						:    List[str]						, A						:    int						, A						:    List[Any]=True						, A						:    List[str]=None	):
             return {
                 "accuracy": float(
                     accuracy_score(A						, A						, normalize=A						, sample_weight=A	)	)
             }

