






"""simple docstring"""



from typing import Dict, Optional

import numpy as np

import datasets


__A		:       Tuple  				=		'''
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		:       List[Any]  				=		'''
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		:       Union[str, Any]  				=		'''\
@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 						lowercase    (				__snake_case				: Tuple		,					__snake_case				: int		,					__snake_case				: Tuple		,					__snake_case				: bool		,					__snake_case				: Optional[Dict[int, int]] = None		,					__snake_case				: bool = False		,					):
		if label_map is not None:
				for old_id, new_id in label_map.items():
						lowercase_ : Any							       =   new_id

    # turn into Numpy arrays
		lowercase_ : str							       =   np.array(__snake_case	)
		lowercase_ : List[str]							       =   np.array(__snake_case	)

		if reduce_labels:
				lowercase_ : Optional[Any]							       =   2_5_5
				lowercase_ : List[Any]							       =   label - 1
				lowercase_ : int							       =   2_5_5

		lowercase_ : Optional[Any]							       =   label != ignore_index
		lowercase_ : Union[str, Any]							       =   np.not_equal(__snake_case		,					__snake_case	)
		lowercase_ : str							       =   pred_label[mask]
		lowercase_ : Optional[Any]							       =   np.array(__snake_case	)[mask]

		lowercase_ : List[str]							       =   pred_label[pred_label == label]

		lowercase_ : Dict							       =   np.histogram(__snake_case		,					bins=__snake_case		,					range=(0, num_labels - 1)	)[0]
		lowercase_ : str							       =   np.histogram(__snake_case		,					bins=__snake_case		,					range=(0, num_labels - 1)	)[0]
		lowercase_ : Union[str, Any]							       =   np.histogram(__snake_case		,					bins=__snake_case		,					range=(0, num_labels - 1)	)[0]

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

		return area_intersect, area_union, area_pred_label, area_label



def 						lowercase    (				__snake_case				: Optional[int]		,					__snake_case				: List[str]		,					__snake_case				: str		,					__snake_case				: bool		,					__snake_case				: Optional[Dict[int, int]] = None		,					__snake_case				: bool = False		,					):
		lowercase_ : Union[str, Any]							       =   np.zeros((num_labels,)		,					dtype=np.floataa	)
		lowercase_ : List[Any]							       =   np.zeros((num_labels,)		,					dtype=np.floataa	)
		lowercase_ : Optional[int]							       =   np.zeros((num_labels,)		,					dtype=np.floataa	)
		lowercase_ : Dict							       =   np.zeros((num_labels,)		,					dtype=np.floataa	)
		for result, gt_seg_map in zip(__snake_case		,					__snake_case	):
				lowercase_       ,					lowercase_       ,					lowercase_       ,					lowercase_ : List[Any]							       =   intersect_and_union(
				    __snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case	)
				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 						lowercase    (				__snake_case				: str		,					__snake_case				: Optional[Any]		,					__snake_case				: Tuple		,					__snake_case				: bool		,					__snake_case				: Optional[int] = None		,					__snake_case				: Optional[Dict[int, int]] = None		,					__snake_case				: bool = False		,					):
		lowercase_       ,					lowercase_       ,					lowercase_       ,					lowercase_ : Any							       =   total_intersect_and_union(
		    __snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case	)

		# compute metrics
		lowercase_ : Dict							       =   {}

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

		lowercase_ : Any							       =   np.nanmean(__snake_case	)
		lowercase_ : Optional[int]							       =   np.nanmean(__snake_case	)
		lowercase_ : Optional[int]							       =   all_acc
		lowercase_ : Any							       =   iou
		lowercase_ : Tuple							       =   acc

		if nan_to_num is not None:
				lowercase_ : int							       =   {metric: np.nan_to_num(__snake_case		,					nan=__snake_case	) for metric, metric_value in metrics.items()}

		return metrics






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




					def   A  (				self     :						Union[str, Any]   )  ->  Tuple:
							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   A  (				self     :						Dict    ,						A     :						Optional[Any]    ,						A     :						Tuple    ,						A     :						int    ,						A     :						bool    ,						A     :						Optional[int] = None    ,						A     :						Optional[Dict[int, int]] = None    ,						A     :						bool = False    ,						)  ->  Dict:
							lowercase_ : Dict							       =   mean_iou(
							    results=A    ,						gt_seg_maps=A    ,						num_labels=A    ,						ignore_index=A    ,						nan_to_num=A    ,						label_map=A    ,						reduce_labels=A    ,						)
							return iou_result











"""simple docstring"""



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFResNetForImageClassification, TFResNetModel
						from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor





class 					_UpperCAmelCase       :




					def __init__(				self     :						int    ,						A     :						Tuple    ,						A     :						int=3    ,						A     :						List[str]=32    ,						A     :						Dict=3    ,						A     :						Any=10    ,						A     :						Dict=[10, 20, 30, 40]    ,						A     :						Optional[Any]=[1, 1, 2, 1]    ,						A     :						Union[str, Any]=True    ,						A     :						Optional[Any]=True    ,						A     :						Any="relu"    ,						A     :						Optional[Any]=3    ,						A     :						Tuple=None    ,						)  ->  Dict:
							lowercase_ : str							       =   parent
							lowercase_ : List[Any]							       =   batch_size
							lowercase_ : Optional[int]							       =   image_size
							lowercase_ : int							       =   num_channels
							lowercase_ : int							       =   embeddings_size
							lowercase_ : str							       =   hidden_sizes
							lowercase_ : List[str]							       =   depths
							lowercase_ : Dict							       =   is_training
							lowercase_ : int							       =   use_labels
							lowercase_ : Any							       =   hidden_act
							lowercase_ : List[Any]							       =   num_labels
							lowercase_ : Tuple							       =   scope
							lowercase_ : Optional[Any]							       =   len(A   )




					def   A  (				self     :						str   )  ->  Tuple:
							lowercase_ : Optional[int]							       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							lowercase_ : Union[str, Any]							       =   None
							if self.use_labels:
									lowercase_ : List[str]							       =   ids_tensor([self.batch_size]    ,						self.num_labels   )

							lowercase_ : Optional[int]							       =   self.get_config()

							return config, pixel_values, labels




					def   A  (				self     :						Dict   )  ->  int:
							return ResNetConfig(
							    num_channels=self.num_channels    ,						embeddings_size=self.embeddings_size    ,						hidden_sizes=self.hidden_sizes    ,						depths=self.depths    ,						hidden_act=self.hidden_act    ,						num_labels=self.num_labels    ,						image_size=self.image_size    ,						)




					def   A  (				self     :						str    ,						A     :						Tuple    ,						A     :						str    ,						A     :						str   )  ->  str:
							lowercase_ : str							       =   TFResNetModel(config=A   )
							lowercase_ : Union[str, Any]							       =   model(A   )
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape    ,						(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,						)




					def   A  (				self     :						Any    ,						A     :						int    ,						A     :						List[Any]    ,						A     :						Optional[Any]   )  ->  Optional[Any]:
							lowercase_ : Tuple							       =   self.num_labels
							lowercase_ : Union[str, Any]							       =   TFResNetForImageClassification(A   )
							lowercase_ : Tuple							       =   model(A    ,						labels=A   )
							self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)   )






					def   A  (				self     :						Union[str, Any]   )  ->  Tuple:
							lowercase_ : Tuple							       =   self.prepare_config_and_inputs()
							lowercase_       ,					lowercase_       ,					lowercase_ : Dict							       =   config_and_inputs
							lowercase_ : int							       =   {'''pixel_values''': pixel_values}
							return config, inputs_dict





@require_tf
class 					_UpperCAmelCase       ( _A   ,						_A   ,						unittest.TestCase							):
					SCREAMING_SNAKE_CASE_		:				Union[str, Any]							    =   (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
					SCREAMING_SNAKE_CASE_		:				List[Any]							    =   (
					    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
					    if is_tf_available()
					    else {}
					)

					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   False
					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   False
					SCREAMING_SNAKE_CASE_		:				str							    =   False
					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   False
					SCREAMING_SNAKE_CASE_		:				Any							    =   False




					def   A  (				self     :						Union[str, Any]   )  ->  List[Any]:
							lowercase_ : int							       =   TFResNetModelTester(self   )
							lowercase_ : str							       =   ConfigTester(self    ,						config_class=A    ,						has_text_modality=A   )




					def   A  (				self     :						Dict   )  ->  Optional[Any]:
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()




					def   A  (				self     :						Dict   )  ->  List[Any]:
							return




					@unittest.skip(reason='''ResNet does not use inputs_embeds'''   )
					def   A  (				self     :						Any   )  ->  Any:
							pass




					@unittest.skip(reason='''ResNet does not support input and output embeddings'''   )
					def   A  (				self     :						List[str]   )  ->  Optional[Any]:
							pass




					def   A  (				self     :						str   )  ->  Tuple:
							lowercase_       ,					lowercase_ : Optional[Any]							       =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowercase_ : int							       =   model_class(A   )
									lowercase_ : str							       =   inspect.signature(model.call   )
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowercase_ : str							       =   [*signature.parameters.keys()]

									lowercase_ : str							       =   ['''pixel_values''']
									self.assertListEqual(arg_names[:1]    ,						A   )




					def   A  (				self     :						List[str]   )  ->  Tuple:
							lowercase_ : Optional[Any]							       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*A   )




					def   A  (				self     :						List[Any]   )  ->  List[str]:
							def check_hidden_states_output(A     :						Union[str, Any]    ,						A     :						int    ,						A     :						List[Any]   ):
									lowercase_ : int							       =   model_class(A   )
									lowercase_ : Optional[Any]							       =   model(**self._prepare_for_class(A    ,						A   )   )

									lowercase_ : Union[str, Any]							       =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									lowercase_ : Any							       =   self.model_tester.num_stages
									self.assertEqual(len(A   )    ,						expected_num_stages + 1   )

									# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]   )    ,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,						)

							lowercase_       ,					lowercase_ : List[Any]							       =   self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_ : Union[str, Any]							       =   ['''basic''', '''bottleneck''']
							for model_class in self.all_model_classes:
									for layer_type in layers_type:
											lowercase_ : List[str]							       =   layer_type
											lowercase_ : Tuple							       =   True
											check_hidden_states_output(A    ,						A    ,						A   )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											lowercase_ : Optional[Any]							       =   True

											check_hidden_states_output(A    ,						A    ,						A   )




					def   A  (				self     :						Optional[int]   )  ->  Tuple:
							lowercase_ : Optional[int]							       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*A   )






					@slow
					def   A  (				self     :						List[str]   )  ->  Optional[int]:
							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowercase_ : Tuple							       =   TFResNetModel.from_pretrained(A   )
									self.assertIsNotNone(A   )



def 						lowercase    (				):
		lowercase_ : List[str]							       =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
		return image






@require_tf
@require_vision
class 					_UpperCAmelCase       ( unittest.TestCase							):




					@cached_property
					def   A  (				self     :						Any   )  ->  Optional[int]:
							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
							    if is_vision_available()
							    else None
							)






					@slow
					def   A  (				self     :						Any   )  ->  Optional[int]:
							lowercase_ : Optional[int]							       =   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

							lowercase_ : List[Any]							       =   self.default_image_processor
							lowercase_ : Dict							       =   prepare_img()
							lowercase_ : List[str]							       =   image_processor(images=A    ,						return_tensors='''tf'''   )

							# forward pass
							lowercase_ : Tuple							       =   model(**A   )

							# verify the logits
							lowercase_ : Optional[int]							       =   tf.TensorShape((1, 10_00)   )
							self.assertEqual(outputs.logits.shape    ,						A   )

							lowercase_ : Optional[Any]							       =   tf.constant([-11.1069, -9.7877, -8.3777]   )

							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,						A    ,						atol=1e-4   )   )



