





"""simple docstring"""






from typing import Dict, Optional

import numpy as np

import datasets


A			      =	"""
IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union
between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,
the mean IoU of the image is calculated by taking the IoU of each class and averaging them.
"""

A			      =	"""
Args:
    predictions (`List[ndarray]`):
        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    references (`List[ndarray]`):
        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    num_labels (`int`):
        Number of classes (categories).
    ignore_index (`int`):
        Index that will be ignored during evaluation.
    nan_to_num (`int`, *optional*):
        If specified, NaN values will be replaced by the number defined by the user.
    label_map (`dict`, *optional*):
        If specified, dictionary mapping old label indices to new label indices.
    reduce_labels (`bool`, *optional*, defaults to `False`):
        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,
        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.

Returns:
    `Dict[str, float | ndarray]` comprising various elements:
    - *mean_iou* (`float`):
        Mean Intersection-over-Union (IoU averaged over all categories).
    - *mean_accuracy* (`float`):
        Mean accuracy (averaged over all categories).
    - *overall_accuracy* (`float`):
        Overall accuracy on all images.
    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):
        Per category accuracy.
    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):
        Per category IoU.

Examples:

    >>> import numpy as np

    >>> mean_iou = datasets.load_metric(\"mean_iou\")

    >>> # suppose one has 3 different segmentation maps predicted
    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])
    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])

    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])
    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])

    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])
    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])

    >>> predicted = [predicted_1, predicted_2, predicted_3]
    >>> ground_truth = [actual_1, actual_2, actual_3]

    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), 'per_category_accuracy': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}
"""

A			      =	"""\
@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,
author = {{MMSegmentation Contributors}},
license = {Apache-2.0},
month = {7},
title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},
url = {https://github.com/open-mmlab/mmsegmentation},
year = {2020}
}"""

def      __A   (      a_    :int ,							a_    :Union[str, Any] ,							a_    :int ,							a_    :Tuple ,							a_    :Optional[int] = None ,							a_    :str = False ,							)		->		Any:



				if label_map is not None:
								for old_id, new_id in label_map.items():
												__a			:    Any      							=	new_id

    # turn into Numpy arrays
				__a			:    int      							=	np.array(a__)
				__a			:    Union[str, Any]      							=	np.array(a__)

				if reduce_labels:
								__a			:    List[Any]      							=	2_55
								__a			:    Any      							=	label - 1
								__a			:    str      							=	2_55

				__a			:    List[str]      							=	label != ignore_index
				__a			:    List[str]      							=	np.not_equal(a__ ,							a__)
				__a			:    List[str]      							=	pred_label[mask]
				__a			:    Any      							=	np.array(a__)[mask]

				__a			:    Dict      							=	pred_label[pred_label == label]

				__a			:    str      							=	np.histogram(a__ ,							bins=a__ ,							range=(0, num_labels - 1))[0]
				__a			:    Union[str, Any]      							=	np.histogram(a__ ,							bins=a__ ,							range=(0, num_labels - 1))[0]
				__a			:    Union[str, Any]      							=	np.histogram(a__ ,							bins=a__ ,							range=(0, num_labels - 1))[0]

				__a			:    Union[str, Any]      							=	area_pred_label + area_label - area_intersect

				return area_intersect, area_union, area_pred_label, area_label

def      __A   (      a_    :Optional[int] ,							a_    :Optional[int] ,							a_    :str ,							a_    :Any ,							a_    :Any = None ,							a_    :Union[str, Any] = False ,							)		->		Any:
				__a			:    Union[str, Any]      							=	np.zeros((num_labels,) ,							dtype=np.floataa)
				__a			:    Optional[Any]      							=	np.zeros((num_labels,) ,							dtype=np.floataa)
				__a			:    Optional[Any]      							=	np.zeros((num_labels,) ,							dtype=np.floataa)
				__a			:    Tuple      							=	np.zeros((num_labels,) ,							dtype=np.floataa)
				for result, gt_seg_map in zip(a__ ,							a__):
								__a			:    Tuple      							=	intersect_and_union(
								    a__ ,							a__ ,							a__ ,							a__ ,							a__ ,							a__)
								total_area_intersect += area_intersect
								total_area_union += area_union
								total_area_pred_label += area_pred_label
								total_area_label += area_label
				return total_area_intersect, total_area_union, total_area_pred_label, total_area_label

def      __A   (      a_    :Tuple ,							a_    :Dict ,							a_    :List[str] ,							a_    :str ,							a_    :str = None ,							a_    :Union[str, Any] = None ,							a_    :Union[str, Any] = False ,							)		->		int:
				__a			:    Union[str, Any]      							=	total_intersect_and_union(
				    a__ ,							a__ ,							a__ ,							a__ ,							a__ ,							a__)

				# compute metrics
				__a			:    Optional[int]      							=	{}

				__a			:    Dict      							=	total_area_intersect.sum() / total_area_label.sum()
				__a			:    Optional[int]      							=	total_area_intersect / total_area_union
				__a			:    List[str]      							=	total_area_intersect / total_area_label

				__a			:    int      							=	np.nanmean(a__)
				__a			:    int      							=	np.nanmean(a__)
				__a			:    Union[str, Any]      							=	all_acc
				__a			:    Optional[Any]      							=	iou
				__a			:    int      							=	acc

				if nan_to_num is not None:
								__a			:    Dict      							=	{metric: np.nan_to_num(a__ ,							nan=a__) for metric, metric_value in metrics.items()}

				return metrics






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







					'''simple docstring'''




					def 			_lowerCamelCase		(    self  ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION						,      citation=_CITATION						,      inputs_description=_KWARGS_DESCRIPTION						,      features=datasets.Features(
									        # 1st Seq - height dim, 2nd - width dim
									        {
									            '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''  )  )  ),
									            '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''  )  )  ),
									        }  )						,      reference_urls=[
									        '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'''
									    ]						,      )







					def 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase = None						,      _UpperCAmelCase = None						,      _UpperCAmelCase = False						,      ):
									__a			:    List[Any]      							=	mean_iou(
									    results=_lowercase						,      gt_seg_maps=_lowercase						,      num_labels=_lowercase						,      ignore_index=_lowercase						,      nan_to_num=_lowercase						,      label_map=_lowercase						,      reduce_labels=_lowercase						,      )
									return iou_result


import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class        A__(a_,  a_,  unittest.TestCase							):
						"""simple docstring"""






						_A    :				Optional[Any]       					=			StableDiffusionSAGPipeline
						_A    :				Any       					=			TEXT_TO_IMAGE_PARAMS
						_A    :				Dict       					=			TEXT_TO_IMAGE_BATCH_PARAMS
						_A    :				Dict       					=			TEXT_TO_IMAGE_IMAGE_PARAMS
						_A    :				int       					=			TEXT_TO_IMAGE_IMAGE_PARAMS
						_A    :				Optional[int]       					=			False





						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									torch.manual_seed(0    )
									a_						:						Tuple 							= UNetaDConditionModel(
									    block_out_channels=(32, 64)  ,      layers_per_block=2  ,      sample_size=32  ,      in_channels=4  ,      out_channels=4  ,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")  ,      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")  ,      cross_attention_dim=32  ,      )
									a_						:						int 							= DDIMScheduler(
									    beta_start=0.0_0_0_8_5  ,      beta_end=0.0_1_2  ,      beta_schedule="""scaled_linear"""  ,      clip_sample=_lowercase  ,      set_alpha_to_one=_lowercase  ,      )
									torch.manual_seed(0    )
									a_						:						Tuple 							= AutoencoderKL(
									    block_out_channels=[32, 64]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]  ,      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]  ,      latent_channels=4  ,      )
									torch.manual_seed(0    )
									a_						:						str 							= CLIPTextConfig(
									    bos_token_id=0  ,      eos_token_id=2  ,      hidden_size=32  ,      intermediate_size=37  ,      layer_norm_eps=1e-05  ,      num_attention_heads=4  ,      num_hidden_layers=5  ,      pad_token_id=1  ,      vocab_size=1_000  ,      )
									a_						:						Union[str, Any] 							= CLIPTextModel(_lowercase    )
									a_						:						int 							= CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

									a_						:						Union[str, Any] 							= {
									    """unet""": unet,
									    """scheduler""": scheduler,
									    """vae""": vae,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """safety_checker""": None,
									    """feature_extractor""": None,
									}
									return components





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase=0    )     -> Dict:
									if str(_lowercase    ).startswith("""mps"""    ):
												a_						:						Optional[int] 							= torch.manual_seed(_lowercase    )
									else:
												a_						:						str 							= torch.Generator(device=_lowercase    ).manual_seed(_lowercase    )
									a_						:						Tuple 							= {
									    """prompt""": """.""",
									    """generator""": generator,
									    """num_inference_steps""": 2,
									    """guidance_scale""": 1.0,
									    """sag_scale""": 1.0,
									    """output_type""": """numpy""",
									}
									return inputs





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									super().test_inference_batch_single_identical(expected_max_diff=3e-3    )







@slow
@require_torch_gpu
class        A__(unittest.TestCase							):
						"""simple docstring"""






						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						Tuple 							= StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4"""    )
									a_						:						List[str] 							= sag_pipe.to(_lowercase    )
									sag_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						Optional[int] 							= """."""
									a_						:						int 							= torch.manual_seed(0    )
									a_						:						Any 							= sag_pipe(
									    [prompt]  ,      generator=_lowercase  ,      guidance_scale=7.5  ,      sag_scale=1.0  ,      num_inference_steps=20  ,      output_type="""np"""    )

									a_						:						Any 							= output.images

									a_						:						Optional[int] 							= image[0, -3:, -3:, -1]

									assert image.shape == (1, 512, 512, 3)
									a_						:						str 							= np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]    )

									assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5e-2





						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									a_						:						Optional[int] 							= StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base"""    )
									a_						:						List[str] 							= sag_pipe.to(_lowercase    )
									sag_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						int 							= """."""
									a_						:						Dict 							= torch.manual_seed(0    )
									a_						:						Union[str, Any] 							= sag_pipe(
									    [prompt]  ,      generator=_lowercase  ,      guidance_scale=7.5  ,      sag_scale=1.0  ,      num_inference_steps=20  ,      output_type="""np"""    )

									a_						:						Optional[Any] 							= output.images

									a_						:						int 							= image[0, -3:, -3:, -1]

									assert image.shape == (1, 512, 512, 3)
									a_						:						Dict 							= np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]    )

									assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5e-2





						def 			UpperCamelCase__					(    self    )     -> Any:
									a_						:						int 							= StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base"""    )
									a_						:						Optional[Any] 							= sag_pipe.to(_lowercase    )
									sag_pipe.set_progress_bar_config(disable=_lowercase    )

									a_						:						List[Any] 							= """."""
									a_						:						str 							= torch.manual_seed(0    )
									a_						:						int 							= sag_pipe(
									    [prompt]  ,      width=768  ,      height=512  ,      generator=_lowercase  ,      guidance_scale=7.5  ,      sag_scale=1.0  ,      num_inference_steps=20  ,      output_type="""np"""  ,      )

									a_						:						Any 							= output.images

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


