






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

			if is_vision_available():
						from transformers import MaskaFormerImageProcessor

if is_vision_available():
			from PIL import Image




class 							snake_case_       :

						"""simple docstring"""



						def __init__(self:					Dict ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					Union[str, Any]=2 ,					__UpperCAmelCase:					Optional[int]=True ,					__UpperCAmelCase:					Union[str, Any]=False ,					__UpperCAmelCase:					Tuple=10 ,					__UpperCAmelCase:					Dict=3 ,					__UpperCAmelCase:					int=32 * 8 ,					__UpperCAmelCase:					List[Any]=32 * 8 ,					__UpperCAmelCase:					int=4 ,					__UpperCAmelCase:					Tuple=64 ,					)    ->     Union[str, Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					parent
											__a					:						Optional[Any]      =					batch_size
											__a					:						List[Any]      =					is_training
											__a					:						Dict      =					use_auxiliary_loss
											__a					:						Optional[int]      =					num_queries
											__a					:						List[Any]      =					num_channels
											__a					:						Optional[int]      =					min_size
											__a					:						List[str]      =					max_size
											__a					:						Tuple      =					num_labels
											__a					:						str      =					hidden_dim
											__a					:						Tuple      =					hidden_dim



						def        UpperCAmelCase__					(self:					List[Any]   )    ->     Tuple:




											'''simple docstring'''



											__a					:						Dict      =					floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
											    __UpperCAmelCase   )

											__a					:						List[Any]      =					torch.ones([self.batch_size, self.min_size, self.max_size] ,					device=__UpperCAmelCase   )

											__a					:						Optional[int]      =					(
											    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,					device=__UpperCAmelCase   ) > 0.5
											).float()
											__a					:						List[str]      =					(torch.rand((self.batch_size, self.num_labels) ,					device=__UpperCAmelCase   ) > 0.5).long()

											__a					:						Union[str, Any]      =					self.get_config()
											return config, pixel_values, pixel_mask, mask_labels, class_labels



						def        UpperCAmelCase__					(self:					Dict   )    ->     List[str]:




											'''simple docstring'''



											__a					:						Dict      =					MaskaFormerConfig(
											    hidden_size=self.hidden_dim ,					)
											__a					:						Union[str, Any]      =					self.num_queries
											__a					:						List[Any]      =					self.num_labels

											__a					:						str      =					[1, 1, 1, 1]
											__a					:						int      =					self.num_channels

											__a					:						Optional[Any]      =					64
											__a					:						Any      =					128
											__a					:						str      =					self.hidden_dim
											__a					:						int      =					self.hidden_dim
											__a					:						Union[str, Any]      =					self.hidden_dim
											return config



						def        UpperCAmelCase__					(self:					List[str]   )    ->     int:




											'''simple docstring'''



											__a      ,			__a      ,			__a      ,			__a      ,			__a					:						Optional[Any]      =					self.prepare_config_and_inputs()
											__a					:						List[Any]      =					{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
											return config, inputs_dict



						def        UpperCAmelCase__					(self:					Union[str, Any] ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					Dict   )    ->     List[str]:




											'''simple docstring'''



											__a					:						List[Any]      =					output.encoder_hidden_states
											__a					:						int      =					output.pixel_decoder_hidden_states
											__a					:						str      =					output.transformer_decoder_hidden_states

											self.parent.assertTrue(len(__UpperCAmelCase   ) ,					len(config.backbone_config.depths   )   )
											self.parent.assertTrue(len(__UpperCAmelCase   ) ,					len(config.backbone_config.depths   )   )
											self.parent.assertTrue(len(__UpperCAmelCase   ) ,					config.decoder_layers   )



						def        UpperCAmelCase__					(self:					int ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Union[str, Any]=False   )    ->     str:




											'''simple docstring'''



											with torch.no_grad():
																__a					:						List[str]      =					MaskaFormerModel(config=__UpperCAmelCase   )
																model.to(__UpperCAmelCase   )
																model.eval()

																__a					:						List[str]      =					model(pixel_values=__UpperCAmelCase ,					pixel_mask=__UpperCAmelCase   )
																__a					:						int      =					model(__UpperCAmelCase ,					output_hidden_states=__UpperCAmelCase   )

											self.parent.assertEqual(
											    output.transformer_decoder_last_hidden_state.shape ,					(self.batch_size, self.num_queries, self.hidden_dim) ,					)
											# let's ensure the other two hidden state exists
											self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None   )
											self.parent.assertTrue(output.encoder_last_hidden_state is not None   )

											if output_hidden_states:
																self.check_output_hidden_state(__UpperCAmelCase ,					__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Union[str, Any] ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					str   )    ->     int:




											'''simple docstring'''



											__a					:						Optional[Any]      =					MaskaFormerForUniversalSegmentation(config=__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.eval()

											def comm_check_on_output(__UpperCAmelCase:					Dict   ):
																# let's still check that all the required stuff is there
																self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None   )
																self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None   )
																self.parent.assertTrue(result.encoder_last_hidden_state is not None   )
																# okay, now we need to check the logits shape
																# due to the encoder compression, masks have a //4 spatial size
																self.parent.assertEqual(
																    result.masks_queries_logits.shape ,					(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,					)
																# + 1 for null class
																self.parent.assertEqual(
																    result.class_queries_logits.shape ,					(self.batch_size, self.num_queries, self.num_labels + 1)   )

											with torch.no_grad():
																__a					:						str      =					model(pixel_values=__UpperCAmelCase ,					pixel_mask=__UpperCAmelCase   )
																__a					:						Union[str, Any]      =					model(__UpperCAmelCase   )

																comm_check_on_output(__UpperCAmelCase   )

																__a					:						Dict      =					model(
																    pixel_values=__UpperCAmelCase ,					pixel_mask=__UpperCAmelCase ,					mask_labels=__UpperCAmelCase ,					class_labels=__UpperCAmelCase   )

											comm_check_on_output(__UpperCAmelCase   )

											self.parent.assertTrue(result.loss is not None   )
											self.parent.assertEqual(result.loss.shape ,					torch.Size([1]   )   )




@require_torch
class 							snake_case_       (    __UpperCamelCase		,							__UpperCamelCase		,							unittest.TestCase      ):

						"""simple docstring"""



						snake_case__        =      (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
						snake_case__        =      {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False



						def        UpperCAmelCase__					(self:					List[str]   )    ->     str:




											'''simple docstring'''



											__a					:						List[str]      =					MaskaFormerModelTester(self   )
											__a					:						Any      =					ConfigTester(self ,					config_class=__UpperCAmelCase ,					has_text_modality=__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					List[Any]   )    ->     Optional[int]:




											'''simple docstring'''



											self.config_tester.run_common_tests()



						def        UpperCAmelCase__					(self:					Any   )    ->     int:




											'''simple docstring'''



											__a      ,			__a					:						Dict      =					self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase ,					**__UpperCAmelCase ,					output_hidden_states=__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Dict   )    ->     int:




											'''simple docstring'''



											__a					:						Optional[Any]      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCAmelCase   )



						@unittest.skip(reason="Mask2Former does not use inputs_embeds"   )
						def        UpperCAmelCase__					(self:					Dict   )    ->     str:




											'''simple docstring'''



											pass



						@unittest.skip(reason="Mask2Former does not have a get_input_embeddings method"   )
						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Union[str, Any]:




											'''simple docstring'''



											pass



						@unittest.skip(reason="Mask2Former is not a generative model"   )
						def        UpperCAmelCase__					(self:					Dict   )    ->     Any:




											'''simple docstring'''



											pass



						@unittest.skip(reason="Mask2Former does not use token embeddings"   )
						def        UpperCAmelCase__					(self:					Any   )    ->     Dict:




											'''simple docstring'''



											pass



						@require_torch_multi_gpu
						@unittest.skip(
						    reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"   )
						def        UpperCAmelCase__					(self:					Dict   )    ->     Any:




											'''simple docstring'''



											pass



						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
						def        UpperCAmelCase__					(self:					str   )    ->     Dict:




											'''simple docstring'''



											pass



						def        UpperCAmelCase__					(self:					str   )    ->     Dict:




											'''simple docstring'''



											__a      ,			__a					:						Tuple      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						Any      =					model_class(__UpperCAmelCase   )
																__a					:						Dict      =					inspect.signature(model.forward   )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																__a					:						List[Any]      =					[*signature.parameters.keys()]

																__a					:						List[str]      =					["pixel_values"]
																self.assertListEqual(arg_names[:1] ,					__UpperCAmelCase   )



						@slow
						def        UpperCAmelCase__					(self:					int   )    ->     List[Any]:




											'''simple docstring'''



											for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
																__a					:						Tuple      =					MaskaFormerModel.from_pretrained(__UpperCAmelCase   )
																self.assertIsNotNone(__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					str   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						List[str]      =					(self.model_tester.min_size,) * 2
											__a					:						int      =					{
											    "pixel_values": torch.randn((2, 3, *size) ,					device=__UpperCAmelCase   ),
											    "mask_labels": torch.randn((2, 10, *size) ,					device=__UpperCAmelCase   ),
											    "class_labels": torch.zeros(2 ,					10 ,					device=__UpperCAmelCase   ).long(),
											}
											__a					:						Dict      =					self.model_tester.get_config()

											__a					:						str      =					MaskaFormerForUniversalSegmentation(__UpperCAmelCase   ).to(__UpperCAmelCase   )
											__a					:						Union[str, Any]      =					model(**__UpperCAmelCase   )
											self.assertTrue(outputs.loss is not None   )



						def        UpperCAmelCase__					(self:					Any   )    ->     Dict:




											'''simple docstring'''



											__a      ,			__a					:						Dict      =					self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase ,					**__UpperCAmelCase ,					output_hidden_states=__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					int   )    ->     Optional[int]:




											'''simple docstring'''



											__a      ,			__a					:						Tuple      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						Dict      =					model_class(__UpperCAmelCase   ).to(__UpperCAmelCase   )
																__a					:						Tuple      =					model(**__UpperCAmelCase ,					output_attentions=__UpperCAmelCase   )
																self.assertTrue(outputs.attentions is not None   )



						def        UpperCAmelCase__					(self:					Tuple   )    ->     Tuple:




											'''simple docstring'''



											if not self.model_tester.is_training:
																return

											__a					:						Union[str, Any]      =					self.all_model_classes[1]
											__a      ,			__a      ,			__a      ,			__a      ,			__a					:						Dict      =					self.model_tester.prepare_config_and_inputs()

											__a					:						Optional[Any]      =					model_class(__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.train()

											__a					:						Optional[int]      =					model(__UpperCAmelCase ,					mask_labels=__UpperCAmelCase ,					class_labels=__UpperCAmelCase   ).loss
											loss.backward()



						def        UpperCAmelCase__					(self:					List[Any]   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						Any      =					self.all_model_classes[1]
											__a      ,			__a      ,			__a      ,			__a      ,			__a					:						Dict      =					self.model_tester.prepare_config_and_inputs()
											__a					:						List[str]      =					True
											__a					:						List[str]      =					True

											__a					:						List[str]      =					model_class(__UpperCAmelCase   ).to(__UpperCAmelCase   )
											model.train()

											__a					:						Tuple      =					model(__UpperCAmelCase ,					mask_labels=__UpperCAmelCase ,					class_labels=__UpperCAmelCase   )

											__a					:						Optional[int]      =					outputs.encoder_hidden_states[0]
											encoder_hidden_states.retain_grad()

											__a					:						Tuple      =					outputs.pixel_decoder_hidden_states[0]
											pixel_decoder_hidden_states.retain_grad()

											__a					:						List[str]      =					outputs.transformer_decoder_hidden_states[0]
											transformer_decoder_hidden_states.retain_grad()

											__a					:						str      =					outputs.attentions[0]
											attentions.retain_grad()

											outputs.loss.backward(retain_graph=__UpperCAmelCase   )

											self.assertIsNotNone(encoder_hidden_states.grad   )
											self.assertIsNotNone(pixel_decoder_hidden_states.grad   )
											self.assertIsNotNone(transformer_decoder_hidden_states.grad   )
											self.assertIsNotNone(attentions.grad   )


UpperCAmelCase__      			=						1e-4







def     a_   ()				->						Any:



					"""simple docstring"""
					__a					:						Optional[Any]      =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
					return image




@require_vision
@slow
class 							snake_case_       (    unittest.TestCase      ):

						"""simple docstring"""



						@cached_property
						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     int:




											'''simple docstring'''



											return "facebook/mask2former-swin-small-coco-instance"



						@cached_property
						def        UpperCAmelCase__					(self:					List[str]   )    ->     Any:




											'''simple docstring'''



											return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints   ) if is_vision_available() else None



						def        UpperCAmelCase__					(self:					str   )    ->     str:




											'''simple docstring'''



											__a					:						str      =					MaskaFormerModel.from_pretrained(self.model_checkpoints   ).to(__UpperCAmelCase   )
											__a					:						Optional[Any]      =					self.default_image_processor
											__a					:						List[Any]      =					prepare_img()
											__a					:						str      =					image_processor(__UpperCAmelCase ,					return_tensors="pt"   ).to(__UpperCAmelCase   )
											__a					:						Tuple      =					inputs["pixel_values"].shape
											# check size is divisible by 32
											self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
											# check size
											self.assertEqual(__UpperCAmelCase ,					(1, 3, 384, 384)   )

											with torch.no_grad():
																__a					:						Tuple      =					model(**__UpperCAmelCase   )

											__a					:						Optional[Any]      =					torch.tensor(
											    [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]   ).to(__UpperCAmelCase   )
											self.assertTrue(
											    torch.allclose(
											        outputs.encoder_last_hidden_state[0, 0, :3, :3] ,					__UpperCAmelCase ,					atol=__UpperCAmelCase   )   )

											__a					:						int      =					torch.tensor(
											    [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]   ).to(__UpperCAmelCase   )
											self.assertTrue(
											    torch.allclose(
											        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,					__UpperCAmelCase ,					atol=__UpperCAmelCase   )   )

											__a					:						Tuple      =					torch.tensor(
											    [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]   ).to(__UpperCAmelCase   )
											self.assertTrue(
											    torch.allclose(
											        outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,					__UpperCAmelCase ,					atol=__UpperCAmelCase   )   )



						def        UpperCAmelCase__					(self:					Tuple   )    ->     str:




											'''simple docstring'''



											__a					:						Dict      =					MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(__UpperCAmelCase   ).eval()
											__a					:						List[Any]      =					self.default_image_processor
											__a					:						Union[str, Any]      =					prepare_img()
											__a					:						List[str]      =					image_processor(__UpperCAmelCase ,					return_tensors="pt"   ).to(__UpperCAmelCase   )
											__a					:						Optional[Any]      =					inputs["pixel_values"].shape
											# check size is divisible by 32
											self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
											# check size
											self.assertEqual(__UpperCAmelCase ,					(1, 3, 384, 384)   )

											with torch.no_grad():
																__a					:						List[Any]      =					model(**__UpperCAmelCase   )
											# masks_queries_logits
											__a					:						Tuple      =					outputs.masks_queries_logits
											self.assertEqual(
											    masks_queries_logits.shape ,					(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)   )
											__a					:						str      =					[
											    [-8.78_39, -9.00_56, -8.81_21],
											    [-7.41_04, -7.03_13, -6.54_01],
											    [-6.61_05, -6.34_27, -6.46_75],
											]
											__a					:						Union[str, Any]      =					torch.tensor(__UpperCAmelCase   ).to(__UpperCAmelCase   )
											self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,					__UpperCAmelCase ,					atol=__UpperCAmelCase   )   )
											# class_queries_logits
											__a					:						Tuple      =					outputs.class_queries_logits
											self.assertEqual(class_queries_logits.shape ,					(1, model.config.num_queries, model.config.num_labels + 1)   )
											__a					:						Optional[int]      =					torch.tensor(
											    [
											        [1.83_24, -8.08_35, -4.19_22],
											        [0.84_50, -9.00_50, -3.60_53],
											        [0.30_45, -7.72_93, -3.02_75],
											    ]   ).to(__UpperCAmelCase   )
											self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,					__UpperCAmelCase ,					atol=__UpperCAmelCase   )   )



						def        UpperCAmelCase__					(self:					List[str]   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						List[str]      =					MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints   ).to(__UpperCAmelCase   ).eval()
											__a					:						List[str]      =					self.default_image_processor

											__a					:						Optional[Any]      =					image_processor(
											    [np.zeros((3, 800, 1333)   ), np.zeros((3, 800, 1333)   )] ,					segmentation_maps=[np.zeros((384, 384)   ).astype(np.floataa   ), np.zeros((384, 384)   ).astype(np.floataa   )] ,					return_tensors="pt" ,					)

											__a					:						Tuple      =					inputs["pixel_values"].to(__UpperCAmelCase   )
											__a					:						Any      =					[el.to(__UpperCAmelCase   ) for el in inputs["mask_labels"]]
											__a					:						List[str]      =					[el.to(__UpperCAmelCase   ) for el in inputs["class_labels"]]

											with torch.no_grad():
																__a					:						Any      =					model(**__UpperCAmelCase   )

											self.assertTrue(outputs.loss is not None   )













from typing import Dict, Optional

import numpy as np

import datasets


UpperCAmelCase__      			=						'''
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.
'''

UpperCAmelCase__      			=						'''
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.        ])}
'''

UpperCAmelCase__      			=						'''\
@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				,       __A				,       __A				,       __A				,       __A = None				,       __A = False				,       )				->						Dict:



					"""simple docstring"""
					if label_map is not None:
										for old_id, new_id in label_map.items():
															__a					:						str      =					new_id

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

					if reduce_labels:
										__a					:						Dict      =					255
										__a					:						Union[str, Any]      =					label - 1
										__a					:						int      =					255

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

					__a					:						Optional[int]      =					pred_label[pred_label == label]

					__a					:						Dict      =					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					:						List[Any]      =					np.histogram(__A				,       bins=__A				,       range=(0, num_labels - 1)      )[0]

					__a					:						Optional[int]      =					area_pred_label + area_label - area_intersect

					return area_intersect, area_union, area_pred_label, area_label







def     a_   (__A				,       __A				,       __A				,       __A				,       __A = None				,       __A = False				,       )				->						Dict:



					"""simple docstring"""
					__a					:						Union[str, Any]      =					np.zeros((num_labels,)				,       dtype=np.floataa      )
					__a					:						List[str]      =					np.zeros((num_labels,)				,       dtype=np.floataa      )
					__a					:						Optional[Any]      =					np.zeros((num_labels,)				,       dtype=np.floataa      )
					__a					:						Optional[int]      =					np.zeros((num_labels,)				,       dtype=np.floataa      )
					for result, gt_seg_map in zip(__A				,       __A      ):
										__a      ,			__a      ,			__a      ,			__a					:						Dict      =					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				,       __A				,       __A				,       __A				,       __A = None				,       __A = None				,       __A = False				,       )				->						Optional[int]:



					"""simple docstring"""
					__a      ,			__a      ,			__a      ,			__a					:						Optional[int]      =					total_intersect_and_union(
					    __A				,       __A				,       __A				,       __A				,       __A				,       __A      )

					# compute metrics
					__a					:						Any      =					{}

					__a					:						str      =					total_area_intersect.sum() / total_area_label.sum()
					__a					:						List[Any]      =					total_area_intersect / total_area_union
					__a					:						Union[str, Any]      =					total_area_intersect / total_area_label

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

					if nan_to_num is not None:
										__a					:						Tuple      =					{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 							snake_case_       (    datasets.Metric      ):

						"""simple docstring"""



						def        UpperCAmelCase__					(self:					List[str]   )    ->     Tuple:




											'''simple docstring'''



											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        UpperCAmelCase__					(self:					Optional[int] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					bool ,					__UpperCAmelCase:					Optional[int] = None ,					__UpperCAmelCase:					Optional[Dict[int, int]] = None ,					__UpperCAmelCase:					bool = False ,					)    ->     List[str]:




											'''simple docstring'''



											__a					:						str      =					mean_iou(
											    results=__UpperCAmelCase ,					gt_seg_maps=__UpperCAmelCase ,					num_labels=__UpperCAmelCase ,					ignore_index=__UpperCAmelCase ,					nan_to_num=__UpperCAmelCase ,					label_map=__UpperCAmelCase ,					reduce_labels=__UpperCAmelCase ,					)
											return iou_result





