


from typing import Dict, Optional

import numpy as np

import datasets


a_ :str  							=			'\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n'

a_ :Tuple  							=			'\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric("mean_iou")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'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.        ])}\n'

a_ :int  							=			'\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}'




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():
                  SCREAMING_SNAKE_CASE__       :  str						     =		new_id

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

      if reduce_labels:
            SCREAMING_SNAKE_CASE__       :  Dict						     =		2_5_5
            SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		label - 1
            SCREAMING_SNAKE_CASE__       :  int						     =		2_5_5

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

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

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

      SCREAMING_SNAKE_CASE__       :  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'''

      SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		np.zeros((num_labels,)      ,    dtype=np.floataa							)
      SCREAMING_SNAKE_CASE__       :  List[str]						     =		np.zeros((num_labels,)      ,    dtype=np.floataa							)
      SCREAMING_SNAKE_CASE__       :  Optional[Any]						     =		np.zeros((num_labels,)      ,    dtype=np.floataa							)
      SCREAMING_SNAKE_CASE__       :  Optional[int]						     =		np.zeros((num_labels,)      ,    dtype=np.floataa							)
      for result, gt_seg_map in zip(__A      ,    __A							):
            SCREAMING_SNAKE_CASE__       :  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'''

      SCREAMING_SNAKE_CASE__       :  Optional[int]						     =		total_intersect_and_union(
          __A      ,    __A      ,    __A      ,    __A      ,    __A      ,    __A							)

      # compute metrics
      SCREAMING_SNAKE_CASE__       :  Any						     =		{}

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

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

      if nan_to_num is not None:
            SCREAMING_SNAKE_CASE__       :  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 							lowercase  (						datasets.Metric			):







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














from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
			import tensorflow as tf

			from transformers import TFBlipTextModel
			from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST




class 							snake_case_       :

						"""simple docstring"""



						def __init__(self:					Optional[Any] ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					int=12 ,					__UpperCAmelCase:					Dict=7 ,					__UpperCAmelCase:					str=True ,					__UpperCAmelCase:					Tuple=True ,					__UpperCAmelCase:					Tuple=True ,					__UpperCAmelCase:					Optional[int]=99 ,					__UpperCAmelCase:					str=32 ,					__UpperCAmelCase:					Any=32 ,					__UpperCAmelCase:					int=2 ,					__UpperCAmelCase:					List[str]=4 ,					__UpperCAmelCase:					Tuple=37 ,					__UpperCAmelCase:					Optional[int]=0.1 ,					__UpperCAmelCase:					List[Any]=0.1 ,					__UpperCAmelCase:					Dict=512 ,					__UpperCAmelCase:					Union[str, Any]=0.02 ,					__UpperCAmelCase:					List[Any]=0 ,					__UpperCAmelCase:					str=None ,					)    ->     Tuple:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					parent
											__a					:						Dict      =					batch_size
											__a					:						Optional[Any]      =					seq_length
											__a					:						int      =					is_training
											__a					:						Union[str, Any]      =					use_input_mask
											__a					:						str      =					use_labels
											__a					:						Tuple      =					vocab_size
											__a					:						Dict      =					hidden_size
											__a					:						Optional[int]      =					projection_dim
											__a					:						Tuple      =					num_hidden_layers
											__a					:						Dict      =					num_attention_heads
											__a					:						Any      =					intermediate_size
											__a					:						Optional[int]      =					dropout
											__a					:						Dict      =					attention_dropout
											__a					:						List[Any]      =					max_position_embeddings
											__a					:						Any      =					initializer_range
											__a					:						Tuple      =					scope
											__a					:						Dict      =					bos_token_id



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




											'''simple docstring'''



											__a					:						Optional[Any]      =					ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size   )

											__a					:						Any      =					None
											if self.use_input_mask:
																__a					:						Tuple      =					random_attention_mask([self.batch_size, self.seq_length]   )

											if input_mask is not None:
																__a					:						Tuple      =					input_mask.numpy()
																__a      ,			__a					:						int      =					input_mask.shape
																__a					:						Dict      =					np.random.randint(1 ,					seq_length - 1 ,					size=(batch_size,)   )
																for batch_idx, start_index in enumerate(__UpperCAmelCase   ):
																					__a					:						Any      =					1
																					__a					:						int      =					0

											__a					:						Union[str, Any]      =					self.get_config()

											return config, input_ids, tf.convert_to_tensor(__UpperCAmelCase   )



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




											'''simple docstring'''



											return BlipTextConfig(
											    vocab_size=self.vocab_size ,					hidden_size=self.hidden_size ,					projection_dim=self.projection_dim ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					dropout=self.dropout ,					attention_dropout=self.attention_dropout ,					max_position_embeddings=self.max_position_embeddings ,					initializer_range=self.initializer_range ,					bos_token_id=self.bos_token_id ,					)



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




											'''simple docstring'''



											__a					:						int      =					TFBlipTextModel(config=__UpperCAmelCase   )
											__a					:						List[str]      =					model(__UpperCAmelCase ,					attention_mask=__UpperCAmelCase ,					training=__UpperCAmelCase   )
											__a					:						Any      =					model(__UpperCAmelCase ,					training=__UpperCAmelCase   )
											self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)   )
											self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.hidden_size)   )



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




											'''simple docstring'''



											__a					:						Tuple      =					self.prepare_config_and_inputs()
											__a      ,			__a      ,			__a					:						Dict      =					config_and_inputs
											__a					:						Union[str, Any]      =					{"input_ids": input_ids, "attention_mask": input_mask}
											return config, inputs_dict




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

						"""simple docstring"""



						snake_case__        =      (TFBlipTextModel,) if is_tf_available() else ()
						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False



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




											'''simple docstring'''



											__a					:						str      =					BlipTextModelTester(self   )
											__a					:						str      =					ConfigTester(self ,					config_class=__UpperCAmelCase ,					hidden_size=37   )



						def        UpperCAmelCase__					(self:					str   )    ->     str:




											'''simple docstring'''



											self.config_tester.run_common_tests()



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




											'''simple docstring'''



											__a					:						int      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Tuple   )    ->     Dict:




											'''simple docstring'''



											pass



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




											'''simple docstring'''



											pass



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




											'''simple docstring'''



											pass



						@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"   )
						def        UpperCAmelCase__					(self:					List[Any]   )    ->     List[str]:




											'''simple docstring'''



											pass



						@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"   )
						def        UpperCAmelCase__					(self:					Union[str, Any]   )    ->     int:




											'''simple docstring'''



											pass



						@slow
						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Tuple:




											'''simple docstring'''



											for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__a					:						List[str]      =					TFBlipTextModel.from_pretrained(__UpperCAmelCase   )
																self.assertIsNotNone(__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Dict ,					__UpperCAmelCase:					Optional[Any]=True   )    ->     Any:




											'''simple docstring'''



											super().test_pt_tf_model_equivalence(allow_missing_keys=__UpperCAmelCase   )





