





from typing import Dict, Optional

import numpy as np

import datasets


_lowerCamelCase			       =      '\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'

_lowerCamelCase			       =      '\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'

_lowerCamelCase			       =      '\\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    __UpperCAmelCase(      lowercase_ ,    lowercase_ ,    lowercase_ ,    lowercase_ ,    lowercase_ = None ,    lowercase_ = False ,    ):
       if label_map is not None:
              for old_id, new_id in label_map.items():
                     _lowerCamelCase							:     Optional[int]	=		new_id

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

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

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

       _lowerCamelCase							:     int	=		pred_label[pred_label == label]

       _lowerCamelCase							:     Optional[int]	=		np.histogram(lowercase_ ,    bins=lowercase_ ,    range=(0, num_labels - 1)      )[0]
       _lowerCamelCase							:     str	=		np.histogram(lowercase_ ,    bins=lowercase_ ,    range=(0, num_labels - 1)      )[0]
       _lowerCamelCase							:     Optional[Any]	=		np.histogram(lowercase_ ,    bins=lowercase_ ,    range=(0, num_labels - 1)      )[0]

       _lowerCamelCase							:     Any	=		area_pred_label + area_label - area_intersect

       return area_intersect, area_union, area_pred_label, area_label




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

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

       _lowerCamelCase							:     str	=		total_area_intersect.sum() / total_area_label.sum()
       _lowerCamelCase							:     Tuple	=		total_area_intersect / total_area_union
       _lowerCamelCase							:     int	=		total_area_intersect / total_area_label

       _lowerCamelCase							:     Dict	=		np.nanmean(lowercase_      )
       _lowerCamelCase							:     Optional[Any]	=		np.nanmean(lowercase_      )
       _lowerCamelCase							:     Any	=		all_acc
       _lowerCamelCase							:     Dict	=		iou
       _lowerCamelCase							:     str	=		acc

       if nan_to_num is not None:
              _lowerCamelCase							:     List[Any]	=		{metric: np.nan_to_num(lowercase_ ,    nan=lowercase_      ) for metric, metric_value in metrics.items()}

       return metrics







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




      """simple docstring"""







      def 				__snake_case			(		self):



             """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 				__snake_case			(		self      ,							a__      ,							a__      ,							a__      ,							a__      ,							a__ = None      ,							a__ = None      ,							a__ = False      ,							):



             """simple docstring"""





             _lowerCamelCase							:     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








import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return x.sum()




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return i + 1







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Tuple	=		{}
             _lowerCamelCase							:     Dict	=		[]
             _lowerCamelCase							:     Optional[Any]	=		1
             _lowerCamelCase							:     Optional[int]	=		[1, 2]
             _lowerCamelCase							:     str	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Dict	=		{'''a''': [1, 2], '''b''': [3, 4]}
             _lowerCamelCase							:     Any	=		{'''a''': {'''1''': 1}, '''b''': 2}
             _lowerCamelCase							:     Optional[Any]	=		{'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
             _lowerCamelCase							:     str	=		{}
             _lowerCamelCase							:     int	=		[]
             _lowerCamelCase							:     str	=		2
             _lowerCamelCase							:     int	=		[2, 3]
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3}
             _lowerCamelCase							:     Tuple	=		{'''a''': [2, 3], '''b''': [4, 5]}
             _lowerCamelCase							:     List[str]	=		{'''a''': {'''1''': 2}, '''b''': 3}
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)

             _lowerCamelCase							:     Dict	=		2
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)

             _lowerCamelCase							:     Any	=		{'''a''': np.eye(2), '''b''': np.zeros(3), '''c''': np.ones(2)}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 2, '''b''': 0, '''c''': 2}
             _lowerCamelCase							:     Optional[int]	=		{
                 '''a''': np.eye(2).astype(a__),
                 '''b''': np.zeros(3).astype(a__),
                 '''c''': np.ones(2).astype(a__),
             }
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             with self.assertRaises(a__):  # can't pickle a local lambda
                    map_nested(lambda a__: x + 1      ,							a__      ,							num_proc=a__)


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 3, '''b''': 4}
             _lowerCamelCase							:     int	=		{'''a''': 5, '''b''': 6}
             _lowerCamelCase							:     Optional[int]	=		sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))])
             self.assertEqual(sorted(zip_dict(a__      ,							a__      ,							a__))      ,							a__)



      def 				__snake_case			(		self):



             """simple docstring"""





             class 			__A       :




                   """simple docstring"""







                   UpperCAmelCase__						=      """bar"""
             _lowerCamelCase							:     Any	=		Foo()
             self.assertEqual(foo.my_attr      ,							'''bar''')
             with temporary_assignment(a__      ,							'''my_attr'''      ,							'''BAR'''):
                    self.assertEqual(foo.my_attr      ,							'''BAR''')
             self.assertEqual(foo.my_attr      ,							'''bar''')




@pytest.mark.parametrize(
    '''iterable_length, num_proc, expected_num_proc''' ,    [
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_ ,    lowercase_      ):
       with patch('''datasets.utils.py_utils._single_map_nested'''      ) as mock_single_map_nested, patch(
           '''datasets.parallel.parallel.Pool'''      ) as mock_multiprocessing_pool:
              _lowerCamelCase							:     Union[str, Any]	=		{F"""{i}""": i for i in range(lowercase_      )}
              _lowerCamelCase							:     List[str]	=		map_nested(lambda lowercase_      : x + 10 ,    lowercase_ ,    num_proc=lowercase_ ,    parallel_min_length=16      )
              if expected_num_proc == 1:
                     assert mock_single_map_nested.called
                     assert not mock_multiprocessing_pool.called
              else:
                     assert not mock_single_map_nested.called
                     assert mock_multiprocessing_pool.called
                     assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      @require_tf
      def 				__snake_case			(		self):



             """simple docstring"""





             import tensorflow as tf
             from tensorflow.keras import layers

             _lowerCamelCase							:     int	=		layers.Dense(2)

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		tf.random.uniform((1, 3))
                    return model(a__).numpy()

             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)


      @require_torch
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		torch.nn.Linear(3      ,							2)
                    _lowerCamelCase							:     Dict	=		torch.rand(1      ,							3)
                    return model(a__).detach().numpy()

             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Optional[int]	=		gen_random_output()
             _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)



      def 				__snake_case			(		self):



             """simple docstring"""





             def gen_random_output():
                    return np.random.rand(1      ,							3)

             with temp_seed(42):
                    _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()
             with temp_seed(42):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)




@pytest.mark.parametrize('''input_data''' ,    [{}]      )
def    __UpperCAmelCase(      lowercase_      ):
       _lowerCamelCase							:     List[Any]	=		NestedDataStructure(lowercase_      ).data
       assert output_data == input_data




@pytest.mark.parametrize(
    '''data, expected_output''' ,    [
        ({}, []),
        ([], []),
        ('''foo''', ['''foo''']),
        (['''foo''', '''bar'''], ['''foo''', '''bar''']),
        ([['''foo''', '''bar''']], ['''foo''', '''bar''']),
        ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']),
        ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']),
        ({'''a''': 1, '''b''': 2}, [1, 2]),
        ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]),
        ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_      ):
       _lowerCamelCase							:     int	=		NestedDataStructure(lowercase_      ).flatten()
       assert output == expected_output




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     Any	=		A(x=1 ,    y='''foobar'''      )
       _lowerCamelCase							:     Union[str, Any]	=		{'''x''': 1, '''y''': '''foobar'''}
       assert asdict(lowercase_      ) == expected_output

       _lowerCamelCase							:     Optional[int]	=		{'''a''': {'''b''': A(x=10 ,    y='''foo'''      )}, '''c''': [A(x=20 ,    y='''bar'''      )]}
       _lowerCamelCase							:     Union[str, Any]	=		{'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]}
       assert asdict(lowercase_      ) == expected_output

       with pytest.raises(lowercase_      ):
              asdict([1, A(x=10 ,    y='''foo'''      )]      )




def    __UpperCAmelCase(      lowercase_      ):
       return text.split()




def    __UpperCAmelCase(      lowercase_      ):
       yield (time.time(), content)
       time.sleep(2      )
       yield (time.time(), content)




def    __UpperCAmelCase(      ):
       with Pool(2      ) as pool:
              _lowerCamelCase							:     Tuple	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check multiprocess from pathos (uses dill for pickling)
       with multiprocess.Pool(2      ) as pool:
              _lowerCamelCase							:     Dict	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check that we get items as fast as possible
       with Pool(2      ) as pool:
              _lowerCamelCase							:     str	=		[]
              for yield_time, content in iflatmap_unordered(
                  lowercase_ ,    _aseconds_generator_of_aitems_with_timing ,    kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}]      ):
                     assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
                     out.append(lowercase_      )
              assert out.count('''a'''      ) == 2
              assert out.count('''b'''      ) == 2
              assert len(lowercase_      ) == 4

