


'''simple docstring'''

from typing import Dict, Optional

import numpy as np

import datasets


_UpperCAmelCase				: int							    =				"""\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"""

_UpperCAmelCase				: 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"""

_UpperCAmelCase				: 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 							__magic_name__(						lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase = None,				lowerCamelCase = False,				):






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

    # turn into Numpy arrays
      __lowerCAmelCase							       =				np.array(__SCREAMING_SNAKE_CASE)
      __lowerCAmelCase							       =				np.array(__SCREAMING_SNAKE_CASE)

      if reduce_labels:
            __lowerCAmelCase							       =				2_5_5
            __lowerCAmelCase							       =				label - 1
            __lowerCAmelCase							       =				2_5_5

      __lowerCAmelCase							       =				label != ignore_index
      __lowerCAmelCase							       =				np.not_equal(__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE)
      __lowerCAmelCase							       =				pred_label[mask]
      __lowerCAmelCase							       =				np.array(__SCREAMING_SNAKE_CASE)[mask]

      __lowerCAmelCase							       =				pred_label[pred_label == label]

      __lowerCAmelCase							       =				np.histogram(__SCREAMING_SNAKE_CASE,				bins=__SCREAMING_SNAKE_CASE,				range=(0, num_labels - 1))[0]
      __lowerCAmelCase							       =				np.histogram(__SCREAMING_SNAKE_CASE,				bins=__SCREAMING_SNAKE_CASE,				range=(0, num_labels - 1))[0]
      __lowerCAmelCase							       =				np.histogram(__SCREAMING_SNAKE_CASE,				bins=__SCREAMING_SNAKE_CASE,				range=(0, num_labels - 1))[0]

      __lowerCAmelCase							       =				area_pred_label + area_label - area_intersect

      return area_intersect, area_union, area_pred_label, area_label

def 							__magic_name__(						lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase = None,				lowerCamelCase = False,				):
      __lowerCAmelCase							       =				np.zeros((num_labels,),				dtype=np.floataa)
      __lowerCAmelCase							       =				np.zeros((num_labels,),				dtype=np.floataa)
      __lowerCAmelCase							       =				np.zeros((num_labels,),				dtype=np.floataa)
      __lowerCAmelCase							       =				np.zeros((num_labels,),				dtype=np.floataa)
      for result, gt_seg_map in zip(__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE):
            __lowerCAmelCase							       =				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 							__magic_name__(						lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase,				lowerCamelCase = None,				lowerCamelCase = None,				lowerCamelCase = False,				):
      __lowerCAmelCase							       =				total_intersect_and_union(
          __SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE,				__SCREAMING_SNAKE_CASE)

      # compute metrics
      __lowerCAmelCase							       =				{}

      __lowerCAmelCase							       =				total_area_intersect.sum() / total_area_label.sum()
      __lowerCAmelCase							       =				total_area_intersect / total_area_union
      __lowerCAmelCase							       =				total_area_intersect / total_area_label

      __lowerCAmelCase							       =				np.nanmean(__SCREAMING_SNAKE_CASE)
      __lowerCAmelCase							       =				np.nanmean(__SCREAMING_SNAKE_CASE)
      __lowerCAmelCase							       =				all_acc
      __lowerCAmelCase							       =				iou
      __lowerCAmelCase							       =				acc

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







    """simple docstring"""



    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       ,			):
          __lowerCAmelCase							       =				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





'''simple docstring'''

import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


_UpperCAmelCase				: Tuple							    =				random.Random()

if is_torch_available():
	import torch

def 							__magic_name__(						lowerCamelCase,				lowerCamelCase=1.0,				lowerCamelCase=None,				lowerCamelCase=None):
						if rng is None:
												__lowerCAmelCase							       =				global_rng

						__lowerCAmelCase							       =				[]
						for batch_idx in range(shape[0]):
												values.append([])
												for _ in range(shape[1]):
																		values[-1].append(rng.random() * scale)

						return values


class       a__				( unittest.TestCase      ):







				"""simple docstring"""



				def __init__(self       ,			__lowercase       ,			__lowercase=7       ,			__lowercase=4_00       ,			__lowercase=20_00       ,			__lowercase=1       ,			__lowercase=0.0       ,			__lowercase=1_60_00       ,			__lowercase=True       ,			__lowercase=True       ,			):
										__lowerCAmelCase							       =				parent
										__lowerCAmelCase							       =				batch_size
										__lowerCAmelCase							       =				min_seq_length
										__lowerCAmelCase							       =				max_seq_length
										__lowerCAmelCase							       =				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										__lowerCAmelCase							       =				feature_size
										__lowerCAmelCase							       =				padding_value
										__lowerCAmelCase							       =				sampling_rate
										__lowerCAmelCase							       =				return_attention_mask
										__lowerCAmelCase							       =				do_normalize




				def 					_snake_case  (self		):
										return {
										    "feature_size": self.feature_size,
										    "padding_value": self.padding_value,
										    "sampling_rate": self.sampling_rate,
										    "return_attention_mask": self.return_attention_mask,
										    "do_normalize": self.do_normalize,
										}




				def 					_snake_case  (self       ,			__lowercase=False       ,			__lowercase=False		):
										def _flatten(__lowercase		):
																return list(itertools.chain(*__lowercase		)		)

										if equal_length:
																__lowerCAmelCase							       =				floats_list((self.batch_size, self.max_seq_length)		)
										else:
																# make sure that inputs increase in size
																__lowerCAmelCase							       =				[
																    _flatten(floats_list((x, self.feature_size)		)		)
																    for x in range(self.min_seq_length       ,			self.max_seq_length       ,			self.seq_length_diff		)
																]

										if numpify:
																__lowerCAmelCase							       =				[np.asarray(__lowercase		) for x in speech_inputs]

										return speech_inputs


@require_torch
@require_torchaudio
class       a__				( __A							,						unittest.TestCase      ):







				"""simple docstring"""



				__UpperCamelCase    :		Union[str, Any]	=	ASTFeatureExtractor




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ASTFeatureExtractionTester(self		)




				def 					_snake_case  (self		):
										# Tests that all call wrap to encode_plus and batch_encode_plus
										__lowerCAmelCase							       =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
										# create three inputs of length 800, 1000, and 1200
										__lowerCAmelCase							       =				[floats_list((1, x)		)[0] for x in range(8_00       ,			14_00       ,			2_00		)]
										__lowerCAmelCase							       =				[np.asarray(__lowercase		) for speech_input in speech_inputs]

										# Test not batched input
										__lowerCAmelCase							       =				feat_extract(speech_inputs[0]       ,			return_tensors='''np'''		).input_values
										__lowerCAmelCase							       =				feat_extract(np_speech_inputs[0]       ,			return_tensors='''np'''		).input_values
										self.assertTrue(np.allclose(__lowercase       ,			__lowercase       ,			atol=1e-3		)		)

										# Test batched
										__lowerCAmelCase							       =				feat_extract(__lowercase       ,			padding=__lowercase       ,			return_tensors='''np'''		).input_values
										__lowerCAmelCase							       =				feat_extract(__lowercase       ,			padding=__lowercase       ,			return_tensors='''np'''		).input_values
										for enc_seq_a, enc_seq_a in zip(__lowercase       ,			__lowercase		):
																self.assertTrue(np.allclose(__lowercase       ,			__lowercase       ,			atol=1e-3		)		)

										# Test 2-D numpy arrays are batched.
										__lowerCAmelCase							       =				[floats_list((1, x)		)[0] for x in (8_00, 8_00, 8_00)]
										__lowerCAmelCase							       =				np.asarray(__lowercase		)
										__lowerCAmelCase							       =				feat_extract(__lowercase       ,			return_tensors='''np'''		).input_values
										__lowerCAmelCase							       =				feat_extract(__lowercase       ,			return_tensors='''np'''		).input_values
										for enc_seq_a, enc_seq_a in zip(__lowercase       ,			__lowercase		):
																self.assertTrue(np.allclose(__lowercase       ,			__lowercase       ,			atol=1e-3		)		)




				@require_torch
				def 					_snake_case  (self		):
										import torch

										__lowerCAmelCase							       =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
										__lowerCAmelCase							       =				np.random.rand(1_00		).astype(np.floataa		)
										__lowerCAmelCase							       =				np_speech_inputs.tolist()

										for inputs in [py_speech_inputs, np_speech_inputs]:
																__lowerCAmelCase							       =				feature_extractor.pad([{'''input_values''': inputs}]       ,			return_tensors='''np'''		)
																self.assertTrue(np_processed.input_values.dtype == np.floataa		)
																__lowerCAmelCase							       =				feature_extractor.pad([{'''input_values''': inputs}]       ,			return_tensors='''pt'''		)
																self.assertTrue(pt_processed.input_values.dtype == torch.floataa		)




				def 					_snake_case  (self       ,			__lowercase		):
										from datasets import load_dataset

										__lowerCAmelCase							       =				load_dataset('''hf-internal-testing/librispeech_asr_dummy'''       ,			'''clean'''       ,			split='''validation'''		)
										# automatic decoding with librispeech
										__lowerCAmelCase							       =				ds.sort('''id'''		).select(range(__lowercase		)		)[:num_samples]['''audio''']

										return [x["array"] for x in speech_samples]




				@require_torch
				def 					_snake_case  (self		):
										# fmt: off
										__lowerCAmelCase							       =				torch.tensor(
										    [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
										     -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
										     -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
										     -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]		)
										# fmt: on

										__lowerCAmelCase							       =				self._load_datasamples(1		)
										__lowerCAmelCase							       =				ASTFeatureExtractor()
										__lowerCAmelCase							       =				feature_extractor(__lowercase       ,			return_tensors='''pt'''		).input_values
										self.assertEquals(input_values.shape       ,			(1, 10_24, 1_28)		)
										self.assertTrue(torch.allclose(input_values[0, 0, :30]       ,			__lowercase       ,			atol=1e-4		)		)

