


'''simple docstring'''


from sklearn.metrics import recall_score

import datasets


UpperCAmelCase_						:  Union[str, Any]				  =						'\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n'


UpperCAmelCase_						:  List[Any]				  =						'\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **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.\n- **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`.\n- **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\'`.\n    - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `\'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.\n    - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **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.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {\'recall\': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {\'recall\': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {\'recall\': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {\'recall\': array([1., 0., 0.])}\n'


UpperCAmelCase_						:  Optional[Any]				  =						'\n@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}\n'





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





							'''simple docstring'''


							def UpperCAmelCase_      (       self    ):
											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 UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case=None       ,   __snake_case=1       ,   __snake_case="binary"       ,   __snake_case=None       ,   __snake_case="warn"       ,   ):
											_SCREAMING_SNAKE_CASE					:			str							= recall_score(
											    __snake_case       ,   __snake_case       ,   labels=__snake_case       ,   pos_label=__snake_case       ,   average=__snake_case       ,   sample_weight=__snake_case       ,   zero_division=__snake_case       ,   )
											return {"recall": float(__snake_case    ) if score.size == 1 else score}








'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class        lowercase__    (		_snake_case	,	unittest.TestCase   ):





							'''simple docstring'''


							A_				: Dict       =    KandinskyVaaPipeline
							A_				: List[str]       =    [
							    """image_embeds""",
							    """negative_image_embeds""",
							]
							A_				: Optional[int]       =    ["""image_embeds""", """negative_image_embeds"""]
							A_				: Optional[Any]       =    [
							    """generator""",
							    """height""",
							    """width""",
							    """latents""",
							    """guidance_scale""",
							    """num_inference_steps""",
							    """return_dict""",
							    """guidance_scale""",
							    """num_images_per_prompt""",
							    """output_type""",
							    """return_dict""",
							]
							A_				: Dict       =    False






							@property
							def UpperCAmelCase_      (       self    ):
											return 32






							@property
							def UpperCAmelCase_      (       self    ):
											return 32






							@property
							def UpperCAmelCase_      (       self    ):
											return self.time_input_dim






							@property
							def UpperCAmelCase_      (       self    ):
											return self.time_input_dim * 4






							@property
							def UpperCAmelCase_      (       self    ):
											return 100






							@property
							def UpperCAmelCase_      (       self    ):
											torch.manual_seed(0    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= {
											    """in_channels""": 4,
											    # Out channels is double in channels because predicts mean and variance
											    """out_channels""": 8,
											    """addition_embed_type""": """image""",
											    """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
											    """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
											    """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
											    """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
											    """layers_per_block""": 1,
											    """encoder_hid_dim""": self.text_embedder_hidden_size,
											    """encoder_hid_dim_type""": """image_proj""",
											    """cross_attention_dim""": self.cross_attention_dim,
											    """attention_head_dim""": 4,
											    """resnet_time_scale_shift""": """scale_shift""",
											    """class_embed_type""": None,
											}

											_SCREAMING_SNAKE_CASE					:			Any							= UNetaDConditionModel(**__snake_case    )
											return model






							@property
							def UpperCAmelCase_      (       self    ):
											return {
											    "block_out_channels": [32, 64],
											    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
											    "in_channels": 3,
											    "latent_channels": 4,
											    "layers_per_block": 1,
											    "norm_num_groups": 8,
											    "norm_type": "spatial",
											    "num_vq_embeddings": 12,
											    "out_channels": 3,
											    "up_block_types": [
											        "AttnUpDecoderBlock2D",
											        "UpDecoderBlock2D",
											    ],
											    "vq_embed_dim": 4,
											}






							@property
							def UpperCAmelCase_      (       self    ):
											torch.manual_seed(0    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= VQModel(**self.dummy_movq_kwargs    )
											return model






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			int							= self.dummy_unet
											_SCREAMING_SNAKE_CASE					:			List[str]							= self.dummy_movq

											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= DDIMScheduler(
											    num_train_timesteps=1000       ,   beta_schedule="""linear"""       ,   beta_start=0.00085       ,   beta_end=0.012       ,   clip_sample=__snake_case       ,   set_alpha_to_one=__snake_case       ,   steps_offset=1       ,   prediction_type="""epsilon"""       ,   thresholding=__snake_case       ,   )

											_SCREAMING_SNAKE_CASE					:			Dict							= {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """movq""": movq,
											}
											return components






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case=0    ):
											_SCREAMING_SNAKE_CASE					:			int							= floats_tensor((1, self.text_embedder_hidden_size)       ,   rng=random.Random(__snake_case    )    ).to(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= floats_tensor((1, self.text_embedder_hidden_size)       ,   rng=random.Random(seed + 1    )    ).to(
											    __snake_case    )
											if str(__snake_case    ).startswith("""mps"""    ):
															_SCREAMING_SNAKE_CASE					:			str							= torch.manual_seed(__snake_case    )
											else:
															_SCREAMING_SNAKE_CASE					:			Dict							= torch.Generator(device=__snake_case    ).manual_seed(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= {
											    """image_embeds""": image_embeds,
											    """negative_image_embeds""": negative_image_embeds,
											    """generator""": generator,
											    """height""": 64,
											    """width""": 64,
											    """guidance_scale""": 4.0,
											    """num_inference_steps""": 2,
											    """output_type""": """np""",
											}
											return inputs






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= """cpu"""

											_SCREAMING_SNAKE_CASE					:			Dict							= self.get_dummy_components()

											_SCREAMING_SNAKE_CASE					:			List[Any]							= self.pipeline_class(**__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= pipe.to(__snake_case    )

											pipe.set_progress_bar_config(disable=__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Any							= pipe(**self.get_dummy_inputs(__snake_case    )    )
											_SCREAMING_SNAKE_CASE					:			Tuple							= output.images

											_SCREAMING_SNAKE_CASE					:			Dict							= pipe(
											    **self.get_dummy_inputs(__snake_case    )       ,   return_dict=__snake_case       ,   )[0]

											_SCREAMING_SNAKE_CASE					:			Tuple							= image[0, -3:, -3:, -1]
											_SCREAMING_SNAKE_CASE					:			List[Any]							= image_from_tuple[0, -3:, -3:, -1]

											assert image.shape == (1, 64, 64, 3)

											_SCREAMING_SNAKE_CASE					:			Dict							= np.array(
											    [0.6237976, 1.0, 0.36441332, 1.0, 0.70639634, 0.29877186, 0.85652125, 0.5216843, 0.54454046]    )

											assert (
											    np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
											), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""

											assert (
											    np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2
											), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""





@slow
@require_torch_gpu
class        lowercase__    (		unittest.TestCase   ):





							'''simple docstring'''


							def UpperCAmelCase_      (       self    ):
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= load_numpy(
											    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
											    """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"""    )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= KandinskyVaaPriorPipeline.from_pretrained(
											    """kandinsky-community/kandinsky-2-2-prior"""       ,   torch_dtype=torch.floataa    )
											pipe_prior.to(__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= KandinskyVaaPipeline.from_pretrained(
											    """kandinsky-community/kandinsky-2-2-decoder"""       ,   torch_dtype=torch.floataa    )
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= pipeline.to(__snake_case    )
											pipeline.set_progress_bar_config(disable=__snake_case    )

											_SCREAMING_SNAKE_CASE					:			Dict							= """red cat, 4k photo"""

											_SCREAMING_SNAKE_CASE					:			List[str]							= torch.Generator(device="""cuda"""    ).manual_seed(0    )
											_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			List[str]							= pipe_prior(
											    __snake_case       ,   generator=__snake_case       ,   num_inference_steps=5       ,   negative_prompt=""""""       ,   ).to_tuple()

											_SCREAMING_SNAKE_CASE					:			Dict							= torch.Generator(device="""cuda"""    ).manual_seed(0    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= pipeline(
											    image_embeds=__snake_case       ,   negative_image_embeds=__snake_case       ,   generator=__snake_case       ,   num_inference_steps=100       ,   output_type="""np"""       ,   )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= output.images[0]

											assert image.shape == (512, 512, 3)

											assert_mean_pixel_difference(__snake_case       ,   __snake_case    )




