



import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import DiffusionPipeline
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import logging


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

class 	lowerCamelCase_    ( a__						):






						'''simple docstring'''







						def __init__(	self      :			Union[str, Any]	,	__lowerCamelCase      :			List[Any]	,	__lowerCamelCase      :			Any	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			List[str]	,	__lowerCamelCase      :			str	,	)      ->				Optional[Any]:
									super().__init__()
									self.register_modules(
									    vae=lowerCamelCase_	,	text_encoder=lowerCamelCase_	,	tokenizer=lowerCamelCase_	,	unet=lowerCamelCase_	,	scheduler=lowerCamelCase_	,	safety_checker=lowerCamelCase_	,	feature_extractor=lowerCamelCase_	,	)







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str	,	__lowerCamelCase      :			Dict = "auto" )      ->				Any:
									if slice_size == "auto":
												# half the attention head size is usually a good trade-off between
												# speed and memory
												A							:					List[Any]              =						self.unet.config.attention_head_dim // 2
									self.unet.set_attention_slice(lowerCamelCase_ )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				Optional[Any]:
									self.enable_attention_slicing(lowerCamelCase_ )







						@torch.no_grad()
						def __call__(	self      :			Optional[Any]	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			str = 5_12	,	__lowerCamelCase      :			str = 5_12	,	__lowerCamelCase      :			Tuple = 50	,	__lowerCamelCase      :			Optional[int] = 7.5	,	__lowerCamelCase      :			Tuple = None	,	__lowerCamelCase      :			List[Any] = 1	,	__lowerCamelCase      :			Optional[Any] = 0.0	,	__lowerCamelCase      :			List[Any] = None	,	__lowerCamelCase      :			int = None	,	__lowerCamelCase      :			Union[str, Any] = "pil"	,	__lowerCamelCase      :			List[Any] = True	,	__lowerCamelCase      :			int = None	,	__lowerCamelCase      :			Optional[int] = 1	,	__lowerCamelCase      :			Dict = None	,	**__lowerCamelCase      :			List[Any]	,	)      ->				Any:

									if isinstance(lowerCamelCase_	,	lowerCamelCase_ ):
												A							:					str              =						1
									elif isinstance(lowerCamelCase_	,	lowerCamelCase_ ):
												A							:					Optional[int]              =						len(lowerCamelCase_ )
									else:
												raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase_ )}""" )

									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}.""" )

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(lowerCamelCase_	,	lowerCamelCase_ ) or callback_steps <= 0)
									):
												raise ValueError(
												    F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
												    F""" {type(lowerCamelCase_ )}.""" )

									# get prompt text embeddings
									A							:					str              =						self.tokenizer(
									    lowerCamelCase_	,	padding="max_length"	,	max_length=self.tokenizer.model_max_length	,	return_tensors="pt"	,	)
									A							:					List[str]              =						text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
												A							:					Optional[int]              =						self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
												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}""" )
												A							:					str              =						text_input_ids[:, : self.tokenizer.model_max_length]

									if text_embeddings is None:
												A							:					Tuple              =						self.text_encoder(text_input_ids.to(self.device ) )[0]

									# duplicate text embeddings for each generation per prompt, using mps friendly method
									A       , A       , A							:					Dict              =						text_embeddings.shape
									A							:					Union[str, Any]              =						text_embeddings.repeat(1	,	lowerCamelCase_	,	1 )
									A							:					int              =						text_embeddings.view(bs_embed * num_images_per_prompt	,	lowerCamelCase_	,	-1 )

									# 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.
									A							:					Optional[Any]              =						guidance_scale > 1.0
									# get unconditional embeddings for classifier free guidance
									if do_classifier_free_guidance:
												A							:					Optional[int]              =						42
												if negative_prompt is None:
															A							:					int              =						[""]
												elif type(lowerCamelCase_ ) is not type(lowerCamelCase_ ):
															raise TypeError(
															    F"""`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase_ )} !="""
															    F""" {type(lowerCamelCase_ )}.""" )
												elif isinstance(lowerCamelCase_	,	lowerCamelCase_ ):
															A							:					Union[str, Any]              =						[negative_prompt]
												elif batch_size != len(lowerCamelCase_ ):
															raise ValueError(
															    F"""`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase_ )}, but `prompt`:"""
															    F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
															    " the batch size of `prompt`." )
												else:
															A							:					Dict              =						negative_prompt

												A							:					Optional[int]              =						text_input_ids.shape[-1]
												A							:					Dict              =						self.tokenizer(
												    lowerCamelCase_	,	padding="max_length"	,	max_length=lowerCamelCase_	,	truncation=lowerCamelCase_	,	return_tensors="pt"	,	)
												A							:					Tuple              =						self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]

												# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
												A							:					Dict              =						uncond_embeddings.shape[1]
												A							:					Optional[Any]              =						uncond_embeddings.repeat(lowerCamelCase_	,	lowerCamelCase_	,	1 )
												A							:					List[Any]              =						uncond_embeddings.view(batch_size * num_images_per_prompt	,	lowerCamelCase_	,	-1 )

												# 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
												A							:					str              =						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`.
									A							:					List[Any]              =						(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
									A							:					Tuple              =						(batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
									A							:					List[Any]              =						text_embeddings.dtype
									if latents is None:
												if self.device.type == "mps":
															# randn does not exist on mps
															A							:					List[str]              =						torch.randn(
															    lowerCamelCase_	,	generator=lowerCamelCase_	,	device="cpu"	,	dtype=lowerCamelCase_ ).to(self.device )
															A							:					Union[str, Any]              =						torch.randn(lowerCamelCase_	,	generator=lowerCamelCase_	,	device="cpu"	,	dtype=lowerCamelCase_ ).to(
															    self.device )
												else:
															A							:					str              =						torch.randn(
															    lowerCamelCase_	,	generator=lowerCamelCase_	,	device=self.device	,	dtype=lowerCamelCase_ )
															A							:					Any              =						torch.randn(lowerCamelCase_	,	generator=lowerCamelCase_	,	device=self.device	,	dtype=lowerCamelCase_ )
									else:
												if latents_reference.shape != latents_shape:
															raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" )
												A							:					Optional[Any]              =						latents_reference.to(self.device )
												A							:					Optional[Any]              =						latents.to(self.device )

									# This is the key part of the pipeline where we
									# try to ensure that the generated images w/ the same seed
									# but different sizes actually result in similar images
									A							:					Optional[Any]              =						(latents_shape[3] - latents_shape_reference[3]) // 2
									A							:					Tuple              =						(latents_shape[2] - latents_shape_reference[2]) // 2
									A							:					Tuple              =						latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
									A							:					Any              =						latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
									A							:					str              =						0 if dx < 0 else dx
									A							:					Tuple              =						0 if dy < 0 else dy
									A							:					List[str]              =						max(-dx	,	0 )
									A							:					List[Any]              =						max(-dy	,	0 )
									# import pdb
									# pdb.set_trace()
									A							:					Tuple              =						latents_reference[:, :, dy : dy + h, dx : dx + w]

									# set timesteps
									self.scheduler.set_timesteps(lowerCamelCase_ )

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

									# scale the initial noise by the standard deviation required by the scheduler
									A							:					List[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]
									A							:					Any              =						"eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
									A							:					Dict              =						{}
									if accepts_eta:
												A							:					Dict              =						eta

									for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ):
												# expand the latents if we are doing classifier free guidance
												A							:					Dict              =						torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
												A							:					str              =						self.scheduler.scale_model_input(lowerCamelCase_	,	lowerCamelCase_ )

												# predict the noise residual
												A							:					Union[str, Any]              =						self.unet(lowerCamelCase_	,	lowerCamelCase_	,	encoder_hidden_states=lowerCamelCase_ ).sample

												# perform guidance
												if do_classifier_free_guidance:
															A       , A							:					Dict              =						noise_pred.chunk(2 )
															A							:					Any              =						noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

												# compute the previous noisy sample x_t -> x_t-1
												A							:					Any              =						self.scheduler.step(lowerCamelCase_	,	lowerCamelCase_	,	lowerCamelCase_	,	**lowerCamelCase_ ).prev_sample

												# call the callback, if provided
												if callback is not None and i % callback_steps == 0:
															callback(lowerCamelCase_	,	lowerCamelCase_	,	lowerCamelCase_ )

									A							:					List[Any]              =						1 / 0.18215 * latents
									A							:					Optional[int]              =						self.vae.decode(lowerCamelCase_ ).sample

									A							:					Dict              =						(image / 2 + 0.5).clamp(0	,	1 )

									# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
									A							:					Optional[int]              =						image.cpu().permute(0	,	2	,	3	,	1 ).float().numpy()

									if self.safety_checker is not None:
												A							:					Optional[Any]              =						self.feature_extractor(self.numpy_to_pil(lowerCamelCase_ )	,	return_tensors="pt" ).to(
												    self.device )
												A       , A							:					Any              =						self.safety_checker(
												    images=lowerCamelCase_	,	clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) )
									else:
												A							:					Optional[int]              =						None

									if output_type == "pil":
												A							:					Dict              =						self.numpy_to_pil(lowerCamelCase_ )

									if not return_dict:
												return (image, has_nsfw_concept)

									return StableDiffusionPipelineOutput(images=lowerCamelCase_	,	nsfw_content_detected=lowerCamelCase_ )




from sklearn.metrics import recall_score

import datasets


__SCREAMING_SNAKE_CASE           =  """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


__SCREAMING_SNAKE_CASE           =  """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


__SCREAMING_SNAKE_CASE           =  """
@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 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				str:
									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.recall_score.html"]	,	)







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Any	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			str=None	,	__lowerCamelCase      :			List[Any]=1	,	__lowerCamelCase      :			Tuple="binary"	,	__lowerCamelCase      :			Tuple=None	,	__lowerCamelCase      :			Tuple="warn"	,	)      ->				Optional[Any]:
									A							:					str              =						recall_score(
									    __lowerCamelCase	,	__lowerCamelCase	,	labels=__lowerCamelCase	,	pos_label=__lowerCamelCase	,	average=__lowerCamelCase	,	sample_weight=__lowerCamelCase	,	zero_division=__lowerCamelCase	,	)
									return {"recall": float(__lowerCamelCase ) if score.size == 1 else score}