
'''simple docstring'''
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
 import importlib_metadata
else:
 import importlib.metadata as importlib_metadata

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE=False       ):
    """simple docstring"""






    try:
        snake_case_ :    Any     			=						os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        snake_case_ :    int     			=						default
    else:
        # KEY is set, convert it to True or False.
        try:
            snake_case_ :    str     			=						strtobool(lowerCAmelCase_       )
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(f'If set, {key} must be yes or no.'       )
    return _value


a_											=						parse_flag_from_env("RUN_SLOW", default=False)
a_											=						parse_flag_from_env("RUN_REMOTE", default=False)
a_											=						parse_flag_from_env("RUN_LOCAL", default=True)
a_											=						parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
a_											=						pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
a_											=						pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
a_											=						pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
a_											=						pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ",
)

# Beam
a_											=						pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
a_											=						pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
a_											=						pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import faiss  # noqa
    except ImportError:
        snake_case_ :    List[Any]     			=						unittest.skip("test requires faiss"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import regex  # noqa
    except ImportError:
        snake_case_ :    List[Any]     			=						unittest.skip("test requires regex"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import elasticsearch  # noqa
    except ImportError:
        snake_case_ :    List[str]     			=						unittest.skip("test requires elasticsearch"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import sqlalchemy  # noqa
    except ImportError:
        snake_case_ :    List[Any]     			=						unittest.skip("test requires sqlalchemy"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not config.TORCH_AVAILABLE:
        snake_case_ :    int     			=						unittest.skip("test requires PyTorch"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not config.TF_AVAILABLE:
        snake_case_ :    Optional[int]     			=						unittest.skip("test requires TensorFlow"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not config.JAX_AVAILABLE:
        snake_case_ :    Union[str, Any]     			=						unittest.skip("test requires JAX"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not config.PIL_AVAILABLE:
        snake_case_ :    List[Any]     			=						unittest.skip("test requires Pillow"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import transformers  # noqa F401
    except ImportError:
        return unittest.skip("test requires transformers"       )(lowerCAmelCase_       )
    else:
        return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip("test requires tiktoken"       )(lowerCAmelCase_       )
    else:
        return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import spacy  # noqa F401
    except ImportError:
        return unittest.skip("test requires spacy"       )(lowerCAmelCase_       )
    else:
        return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    def _require_spacy_model(__SCREAMING_SNAKE_CASE       ):
        try:
            import spacy  # noqa F401

            spacy.load(lowerCAmelCase_       )
        except ImportError:
            return unittest.skip("test requires spacy"       )(lowerCAmelCase_       )
        except OSError:
            return unittest.skip("test requires spacy model '{}'".format(lowerCAmelCase_       )       )(lowerCAmelCase_       )
        else:
            return test_case

    return _require_spacy_model

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import pyspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires pyspark"       )(lowerCAmelCase_       )
    else:
        return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires joblibspark"       )(lowerCAmelCase_       )
    else:
        return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not _run_slow_tests or _run_slow_tests == 0:
        snake_case_ :    Union[str, Any]     			=						unittest.skip("test is slow"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not _run_local_tests or _run_local_tests == 0:
        snake_case_ :    int     			=						unittest.skip("test is local"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not _run_packaged_tests or _run_packaged_tests == 0:
        snake_case_ :    Tuple     			=						unittest.skip("test is packaged"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    if not _run_remote_tests or _run_remote_tests == 0:
        snake_case_ :    List[str]     			=						unittest.skip("test requires remote"       )(lowerCAmelCase_       )
    return test_case

def 						UpperCamelCase_     (	*__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    def decorate(cls       ):
        for name, fn in cls.__dict__.items():
            if callable(lowerCAmelCase_       ) and name.startswith("test"       ):
                for decorator in decorators:
                    snake_case_ :    Dict     			=						decorator(lowerCAmelCase_       )
                setattr(cls,		lowerCAmelCase_,		lowerCAmelCase_       )
        return cls

    return decorate






class    UpperCAmelCase_				(	__lowerCamelCase					):
 pass






class    UpperCAmelCase_				(	__lowerCamelCase					):
 UpperCAmelCase_		    =						0
 UpperCAmelCase_		    =						1
 UpperCAmelCase_		    =						2


@contextmanager
def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE=OfflineSimulationMode.CONNECTION_FAILS,		__SCREAMING_SNAKE_CASE=1E-16       ):
    """simple docstring"""






    snake_case_ :    Optional[Any]     			=						requests.Session().request

    def timeout_request(__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		**__SCREAMING_SNAKE_CASE       ):
        # Change the url to an invalid url so that the connection hangs
        snake_case_ :    Optional[Any]     			=						"https://10.255.255.1"
        if kwargs.get("timeout"       ) is None:
            raise RequestWouldHangIndefinitelyError(
                f'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'       )
        snake_case_ :    Dict     			=						timeout
        try:
            return online_request(lowerCAmelCase_,		lowerCAmelCase_,		**lowerCAmelCase_       )
        except Exception as e:
            # The following changes in the error are just here to make the offline timeout error prettier
            snake_case_ :    str     			=						url
            snake_case_ :    Dict     			=						e.args[0]
            snake_case_ :    Dict     			=						(max_retry_error.args[0].replace("10.255.255.1",		f'OfflineMock[{url}]'       ),)
            snake_case_ :    Tuple     			=						(max_retry_error,)
            raise

    def raise_connection_error(__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		**__SCREAMING_SNAKE_CASE       ):
        raise requests.ConnectionError("Offline mode is enabled.",		request=lowerCAmelCase_       )

    if mode is OfflineSimulationMode.CONNECTION_FAILS:
        with patch("requests.Session.send",		lowerCAmelCase_       ):
            yield
    elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
        # inspired from https://stackoverflow.com/a/904609
        with patch("requests.Session.request",		lowerCAmelCase_       ):
            yield
    elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
        with patch("datasets.config.HF_DATASETS_OFFLINE",		lowerCAmelCase_       ):
            yield
    else:
        raise ValueError("Please use a value from the OfflineSimulationMode enum."       )

@contextmanager
def 						UpperCamelCase_     (	*__SCREAMING_SNAKE_CASE,		**__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    snake_case_ :    List[Any]     			=						str(Path().resolve()       )
    with tempfile.TemporaryDirectory(*lowerCAmelCase_,		**lowerCAmelCase_       ) as tmp_dir:
        try:
            os.chdir(lowerCAmelCase_       )
            yield
        finally:
            os.chdir(lowerCAmelCase_       )

@contextmanager
def 						UpperCamelCase_     (	):
    """simple docstring"""






    import gc

    gc.collect()
    snake_case_ :    Optional[Any]     			=						pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def 						UpperCamelCase_     (	):
    """simple docstring"""






    import gc

    gc.collect()
    snake_case_ :    Any     			=						pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    return deepcopy(lowerCAmelCase_       ).integers(0,		1_0_0,		1_0       ).tolist() == deepcopy(lowerCAmelCase_       ).integers(0,		1_0_0,		1_0       ).tolist()

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(__SCREAMING_SNAKE_CASE,		*__SCREAMING_SNAKE_CASE,		**__SCREAMING_SNAKE_CASE       ):
        try:
            return func(*lowerCAmelCase_,		**lowerCAmelCase_       )
        except HTTPError as err:
            if str(lowerCAmelCase_       ).startswith("500"       ) or str(lowerCAmelCase_       ).startswith("502"       ):
                pytest.xfail(str(lowerCAmelCase_       )       )
            raise err

    return decorator.decorator(_wrapper,		lowerCAmelCase_       )






class    UpperCAmelCase_				:





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    List[str]     			=						returncode
     snake_case_ :    Dict     			=						stdout
     snake_case_ :    int     			=						stderr


async def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    while True:
        snake_case_ :    List[Any]     			=						await stream.readline()
        if line:
            callback(lowerCAmelCase_       )
        else:
            break

async def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=False,		__SCREAMING_SNAKE_CASE=False       ):
    """simple docstring"""






    if echo:
        print("\nRunning: ",		" ".join(lowerCAmelCase_       )       )

    snake_case_ :    str     			=						await asyncio.create_subprocess_exec(
        cmd[0],		*cmd[1:],		stdin=lowerCAmelCase_,		stdout=asyncio.subprocess.PIPE,		stderr=asyncio.subprocess.PIPE,		env=lowerCAmelCase_,		)

    # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
    # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
    #
    # If it starts hanging, will need to switch to the following code. The problem is that no data
    # will be seen until it's done and if it hangs for example there will be no debug info.
    # out, err = await p.communicate()
    # return _RunOutput(p.returncode, out, err)

    snake_case_ :    str     			=						[]
    snake_case_ :    Tuple     			=						[]

    def tee(__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE=""       ):
        snake_case_ :    Union[str, Any]     			=						line.decode("utf-8"       ).rstrip()
        sink.append(lowerCAmelCase_       )
        if not quiet:
            print(lowerCAmelCase_,		lowerCAmelCase_,		file=lowerCAmelCase_       )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            _read_stream(p.stdout,		lambda __SCREAMING_SNAKE_CASE       : tee(lowerCAmelCase_,		lowerCAmelCase_,		sys.stdout,		label="stdout:"       )       ),
            _read_stream(p.stderr,		lambda __SCREAMING_SNAKE_CASE       : tee(lowerCAmelCase_,		lowerCAmelCase_,		sys.stderr,		label="stderr:"       )       ),
        ],		timeout=lowerCAmelCase_,		)
    return _RunOutput(await p.wait(),		lowerCAmelCase_,		lowerCAmelCase_       )

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=1_8_0,		__SCREAMING_SNAKE_CASE=False,		__SCREAMING_SNAKE_CASE=True       ):
    """simple docstring"""






    snake_case_ :    List[Any]     			=						asyncio.get_event_loop()
    snake_case_ :    List[str]     			=						loop.run_until_complete(
        _stream_subprocess(lowerCAmelCase_,		env=lowerCAmelCase_,		stdin=lowerCAmelCase_,		timeout=lowerCAmelCase_,		quiet=lowerCAmelCase_,		echo=lowerCAmelCase_       )       )

    snake_case_ :    int     			=						" ".join(lowerCAmelCase_       )
    if result.returncode > 0:
        snake_case_ :    Any     			=						"\n".join(result.stderr       )
        raise RuntimeError(
            f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
            f'The combined stderr from workers follows:\n{stderr}'       )

    # check that the subprocess actually did run and produced some output, should the test rely on
    # the remote side to do the testing
    if not result.stdout and not result.stderr:
        raise RuntimeError(f'\'{cmd_str}\' produced no output.'       )

    return result

def 						UpperCamelCase_     (	):
    """simple docstring"""






    snake_case_ :    int     			=						os.environ.get("PYTEST_XDIST_WORKER",		"gw0"       )
    snake_case_ :    Dict     			=						re.sub(r"^gw",		"",		lowerCAmelCase_,		0,		re.M       )
    return int(lowerCAmelCase_       )


def 						UpperCamelCase_     (	):
    """simple docstring"""






    snake_case_ :    Optional[Any]     			=						2_9_5_0_0
    snake_case_ :    Optional[Any]     			=						pytest_xdist_worker_id()
    return port + uniq_delta






'''simple docstring'''
from typing import Dict, Optional

import numpy as np

import datasets


a_											=						"\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_											=						"\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_											=						"\\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_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE = None,		__SCREAMING_SNAKE_CASE = False,		):
    """simple docstring"""






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

    # turn into Numpy arrays
    snake_case_ :    int     			=						np.array(__SCREAMING_SNAKE_CASE       )
    snake_case_ :    Any     			=						np.array(__SCREAMING_SNAKE_CASE       )

    if reduce_labels:
        snake_case_ :    str     			=						2_5_5
        snake_case_ :    str     			=						label - 1
        snake_case_ :    List[Any]     			=						2_5_5

    snake_case_ :    Union[str, Any]     			=						label != ignore_index
    snake_case_ :    Dict     			=						np.not_equal(__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       )
    snake_case_ :    Tuple     			=						pred_label[mask]
    snake_case_ :    Any     			=						np.array(__SCREAMING_SNAKE_CASE       )[mask]

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

    snake_case_ :    int     			=						np.histogram(__SCREAMING_SNAKE_CASE,		bins=__SCREAMING_SNAKE_CASE,		range=(0, num_labels - 1)       )[0]
    snake_case_ :    Tuple     			=						np.histogram(__SCREAMING_SNAKE_CASE,		bins=__SCREAMING_SNAKE_CASE,		range=(0, num_labels - 1)       )[0]
    snake_case_ :    List[Any]     			=						np.histogram(__SCREAMING_SNAKE_CASE,		bins=__SCREAMING_SNAKE_CASE,		range=(0, num_labels - 1)       )[0]

    snake_case_ :    List[Any]     			=						area_pred_label + area_label - area_intersect

    return area_intersect, area_union, area_pred_label, area_label

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE = None,		__SCREAMING_SNAKE_CASE = False,		):
    """simple docstring"""






    snake_case_ :    List[Any]     			=						np.zeros((num_labels,),		dtype=np.floataa       )
    snake_case_ :    List[str]     			=						np.zeros((num_labels,),		dtype=np.floataa       )
    snake_case_ :    int     			=						np.zeros((num_labels,),		dtype=np.floataa       )
    snake_case_ :    int     			=						np.zeros((num_labels,),		dtype=np.floataa       )
    for result, gt_seg_map in zip(__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       ):
        snake_case_			, snake_case_			, snake_case_			, snake_case_ :    int     			=						intersect_and_union(
            __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_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 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE = None,		__SCREAMING_SNAKE_CASE = None,		__SCREAMING_SNAKE_CASE = False,		):
    """simple docstring"""






    snake_case_			, snake_case_			, snake_case_			, snake_case_ :    Tuple     			=						total_intersect_and_union(
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       )

    # compute metrics
    snake_case_ :    Union[str, Any]     			=						{}

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

    snake_case_ :    List[str]     			=						np.nanmean(__SCREAMING_SNAKE_CASE       )
    snake_case_ :    str     			=						np.nanmean(__SCREAMING_SNAKE_CASE       )
    snake_case_ :    Any     			=						all_acc
    snake_case_ :    Union[str, Any]     			=						iou
    snake_case_ :    Tuple     			=						acc

    if nan_to_num is not None:
        snake_case_ :    str     			=						{metric: np.nan_to_num(__SCREAMING_SNAKE_CASE,		nan=__SCREAMING_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        snake_case__		(    self):
     return datasets.MetricInfo(
         description=_DESCRIPTION ,       citation=_CITATION ,       inputs_description=_KWARGS_DESCRIPTION ,       features=datasets.Features(
             # 1st Seq - height dim, 2nd - width dim
             {
                 "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16"))),
                 "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16"))),
             }) ,       reference_urls=[
             "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py"
         ] ,       )





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ = None ,       lowercase_ = None ,       lowercase_ = False ,       ):
     snake_case_ :    Optional[Any]     			=						mean_iou(
         results=lowercase_ ,       gt_seg_maps=lowercase_ ,       num_labels=lowercase_ ,       ignore_index=lowercase_ ,       nan_to_num=lowercase_ ,       label_map=lowercase_ ,       reduce_labels=lowercase_ ,       )
     return iou_result




