





"""simple docstring"""




from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

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


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
       TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
       TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
       TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
       LayoutLMvaConfig,
       TFLayoutLMvaForQuestionAnswering,
       TFLayoutLMvaForSequenceClassification,
       TFLayoutLMvaForTokenClassification,
       TFLayoutLMvaModel,
   )

if is_vision_available():
   from PIL import Image

   from transformers import LayoutLMvaImageProcessor

class  _UpperCAmelCase  :



      '''simple docstring'''

      def __init__(     self					,      snake_case_					,      snake_case_=2					,      snake_case_=3					,      snake_case_=4					,      snake_case_=2					,      snake_case_=7					,      snake_case_=True					,      snake_case_=True					,      snake_case_=True					,      snake_case_=True					,      snake_case_=9_9					,      snake_case_=3_6					,      snake_case_=2					,      snake_case_=4					,      snake_case_=3_7					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=5_1_2					,      snake_case_=1_6					,      snake_case_=2					,      snake_case_=0.02					,      snake_case_=6					,      snake_case_=6					,      snake_case_=3					,      snake_case_=4					,      snake_case_=None					,      snake_case_=1_0_0_0					,      ):

        """simple docstring"""

        A_  :       List[Any]										=  parent
        A_  :       int										=  batch_size
        A_  :       List[str]										=  num_channels
        A_  :       Any										=  image_size
        A_  :       List[str]										=  patch_size
        A_  :       Dict										=  is_training
        A_  :       Optional[int]										=  use_input_mask
        A_  :       int										=  use_token_type_ids
        A_  :       Dict										=  use_labels
        A_  :       Tuple										=  vocab_size
        A_  :       List[str]										=  hidden_size
        A_  :       Tuple										=  num_hidden_layers
        A_  :       Dict										=  num_attention_heads
        A_  :       str										=  intermediate_size
        A_  :       Optional[Any]										=  hidden_act
        A_  :       List[Any]										=  hidden_dropout_prob
        A_  :       int										=  attention_probs_dropout_prob
        A_  :       Any										=  max_position_embeddings
        A_  :       Optional[Any]										=  type_vocab_size
        A_  :       int										=  type_sequence_label_size
        A_  :       Optional[Any]										=  initializer_range
        A_  :       Union[str, Any]										=  coordinate_size
        A_  :       Optional[int]										=  shape_size
        A_  :       int										=  num_labels
        A_  :       List[Any]										=  num_choices
        A_  :       str										=  scope
        A_  :       List[Any]										=  range_bbox

        # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
        A_  :       Tuple										=  text_seq_length
        A_  :       Union[str, Any]										=  (image_size // patch_size) ** 2 + 1
        A_  :       List[Any]										=  self.text_seq_length + self.image_seq_length

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       str										=  ids_tensor([self.batch_size, self.text_seq_length]					,      self.vocab_size  )

        A_  :       List[Any]										=  ids_tensor([self.batch_size, self.text_seq_length, 4]					,      self.range_bbox  )
        A_  :       Union[str, Any]										=  bbox.numpy()
        # Ensure that bbox is legal
        for i in range(bbox.shape[0]  ):
          for j in range(bbox.shape[1]  ):
            if bbox[i, j, 3] < bbox[i, j, 1]:
              A_  :       Any										=  bbox[i, j, 3]
              A_  :       Union[str, Any]										=  bbox[i, j, 1]
              A_  :       Optional[Any]										=  tmp_coordinate
            if bbox[i, j, 2] < bbox[i, j, 0]:
              A_  :       Any										=  bbox[i, j, 2]
              A_  :       Optional[int]										=  bbox[i, j, 0]
              A_  :       Tuple										=  tmp_coordinate
        A_  :       Dict										=  tf.constant(snake_case_  )

        A_  :       Union[str, Any]										=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        A_  :       Union[str, Any]										=  None
        if self.use_input_mask:
          A_  :       Optional[int]										=  random_attention_mask([self.batch_size, self.text_seq_length]  )

        A_  :       List[str]										=  None
        if self.use_token_type_ids:
          A_  :       Optional[Any]										=  ids_tensor([self.batch_size, self.text_seq_length]					,      self.type_vocab_size  )

        A_  :       Optional[int]										=  None
        A_  :       str										=  None
        if self.use_labels:
          A_  :       Dict										=  ids_tensor([self.batch_size]					,      self.type_sequence_label_size  )
          A_  :       Dict										=  ids_tensor([self.batch_size, self.text_seq_length]					,      self.num_labels  )

        A_  :       List[str]										=  LayoutLMvaConfig(
            vocab_size=self.vocab_size					,      hidden_size=self.hidden_size					,      num_hidden_layers=self.num_hidden_layers					,      num_attention_heads=self.num_attention_heads					,      intermediate_size=self.intermediate_size					,      hidden_act=self.hidden_act					,      hidden_dropout_prob=self.hidden_dropout_prob					,      attention_probs_dropout_prob=self.attention_probs_dropout_prob					,      max_position_embeddings=self.max_position_embeddings					,      type_vocab_size=self.type_vocab_size					,      initializer_range=self.initializer_range					,      coordinate_size=self.coordinate_size					,      shape_size=self.shape_size					,      input_size=self.image_size					,      patch_size=self.patch_size					,      )

        return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  TFLayoutLMvaModel(config=snake_case_  )

        # text + image
        A_  :       int										=  model(snake_case_					,      pixel_values=snake_case_					,      training=snake_case_  )
        A_  :       Optional[Any]										=  model(
            snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      training=snake_case_					,      )
        A_  :       Any										=  model(snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      training=snake_case_  )

        self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)  )

        # text only
        A_  :       List[str]										=  model(snake_case_					,      training=snake_case_  )
        self.parent.assertEqual(
            result.last_hidden_state.shape					,      (self.batch_size, self.text_seq_length, self.hidden_size)  )

        # image only
        A_  :       Optional[Any]										=  model({'pixel_values': pixel_values}					,      training=snake_case_  )
        self.parent.assertEqual(
            result.last_hidden_state.shape					,      (self.batch_size, self.image_seq_length, self.hidden_size)  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       int										=  self.num_labels
        A_  :       Optional[int]										=  TFLayoutLMvaForSequenceClassification(config=snake_case_  )
        A_  :       List[Any]										=  model(
            snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_					,      training=snake_case_					,      )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       List[str]										=  self.num_labels
        A_  :       int										=  TFLayoutLMvaForTokenClassification(config=snake_case_  )
        A_  :       str										=  model(
            snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_					,      training=snake_case_					,      )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.text_seq_length, self.num_labels)  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       Dict										=  2
        A_  :       Union[str, Any]										=  TFLayoutLMvaForQuestionAnswering(config=snake_case_  )
        A_  :       str										=  model(
            snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      start_positions=snake_case_					,      end_positions=snake_case_					,      training=snake_case_					,      )
        self.parent.assertEqual(result.start_logits.shape					,      (self.batch_size, self.seq_length)  )
        self.parent.assertEqual(result.end_logits.shape					,      (self.batch_size, self.seq_length)  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Any										=  self.prepare_config_and_inputs()
        ((A_)						,       (A_)						,       (A_)						,       (A_)						,       (A_)						,       (A_)						,       (A_)						,       (A_))  :       List[Any]										=  config_and_inputs
        A_  :       Dict										=  {
            'input_ids': input_ids,
            'bbox': bbox,
            'pixel_values': pixel_values,
            'token_type_ids': token_type_ids,
            'attention_mask': input_mask,
        }
        return config, inputs_dict


@require_tf
class  _UpperCAmelCase  (   __SCREAMING_SNAKE_CASE			,   __SCREAMING_SNAKE_CASE			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : Any	    =   (
          (
              TFLayoutLMvaModel,
              TFLayoutLMvaForQuestionAnswering,
              TFLayoutLMvaForSequenceClassification,
              TFLayoutLMvaForTokenClassification,
          )
          if is_tf_available()
          else ()
      )
      lowercase_      : Optional[int]	    =   (
          {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
          if is_tf_available()
          else {}
      )

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

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        return True

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_=False  ):

        """simple docstring"""

        A_  :       Tuple										=  copy.deepcopy(snake_case_  )

        if model_class in get_values(snake_case_  ):
          A_  :       Any										=  {
              k: tf.tile(tf.expand_dims(snake_case_					,      1  )					,      (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)  )
              if isinstance(snake_case_					,      tf.Tensor  ) and v.ndim > 0
              else v
              for k, v in inputs_dict.items()
          }

        if return_labels:
          if model_class in get_values(snake_case_  ):
            A_  :       Optional[int]										=  tf.ones(self.model_tester.batch_size					,      dtype=tf.intaa  )
          elif model_class in get_values(snake_case_  ):
            A_  :       Tuple										=  tf.zeros(self.model_tester.batch_size					,      dtype=tf.intaa  )
            A_  :       Dict										=  tf.zeros(self.model_tester.batch_size					,      dtype=tf.intaa  )
          elif model_class in get_values(snake_case_  ):
            A_  :       str										=  tf.zeros(self.model_tester.batch_size					,      dtype=tf.intaa  )
          elif model_class in get_values(snake_case_  ):
            A_  :       str										=  tf.zeros(
                (self.model_tester.batch_size, self.model_tester.text_seq_length)					,      dtype=tf.intaa  )

        return inputs_dict

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  TFLayoutLMvaModelTester(self  )
        A_  :       Dict										=  ConfigTester(self					,      config_class=snake_case_					,      hidden_size=3_7  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        self.config_tester.run_common_tests()

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_  :       Dict										=  self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
          A_  :       Dict										=  model_class(snake_case_  )
          if getattr(snake_case_					,      'hf_compute_loss'					,      snake_case_  ):
            # The number of elements in the loss should be the same as the number of elements in the label
            A_  :       str										=  self._prepare_for_class(inputs_dict.copy()					,      snake_case_					,      return_labels=snake_case_  )
            A_  :       Any										=  prepared_for_class[
                sorted(prepared_for_class.keys() - inputs_dict.keys()					,      reverse=snake_case_  )[0]
            ]
            A_  :       Tuple										=  added_label.shape.as_list()[:1]

            # Test that model correctly compute the loss with kwargs
            A_  :       Optional[int]										=  self._prepare_for_class(inputs_dict.copy()					,      snake_case_					,      return_labels=snake_case_  )
            A_  :       Optional[Any]										=  prepared_for_class.pop('input_ids'  )

            A_  :       str										=  model(snake_case_					,      **snake_case_  )[0]
            self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

            # Test that model correctly compute the loss when we mask some positions
            A_  :       Dict										=  self._prepare_for_class(inputs_dict.copy()					,      snake_case_					,      return_labels=snake_case_  )
            A_  :       str										=  prepared_for_class.pop('input_ids'  )
            if "labels" in prepared_for_class:
              A_  :       Dict										=  prepared_for_class['labels'].numpy()
              if len(labels.shape  ) > 1 and labels.shape[1] != 1:
                A_  :       Optional[int]										=  -1_0_0
                A_  :       List[Any]										=  tf.convert_to_tensor(snake_case_  )
                A_  :       Tuple										=  model(snake_case_					,      **snake_case_  )[0]
                self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )
                self.assertTrue(not np.any(np.isnan(loss.numpy()  )  )  )

                # Test that model correctly compute the loss with a dict
            A_  :       Union[str, Any]										=  self._prepare_for_class(inputs_dict.copy()					,      snake_case_					,      return_labels=snake_case_  )
            A_  :       List[Any]										=  model(snake_case_  )[0]
            self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

            # Test that model correctly compute the loss with a tuple
            A_  :       List[Any]										=  self._prepare_for_class(inputs_dict.copy()					,      snake_case_					,      return_labels=snake_case_  )

            # Get keys that were added with the _prepare_for_class function
            A_  :       Union[str, Any]										=  prepared_for_class.keys() - inputs_dict.keys()
            A_  :       Optional[Any]										=  inspect.signature(model.call  ).parameters
            A_  :       Optional[Any]										=  list(signature.keys()  )

            # Create a dictionary holding the location of the tensors in the tuple
            A_  :       Union[str, Any]										=  {0: 'input_ids'}
            for label_key in label_keys:
              A_  :       Tuple										=  signature_names.index(snake_case_  )
              A_  :       str										=  label_key
            A_  :       List[Any]										=  sorted(tuple_index_mapping.items()  )
            # Initialize a list with their default values, update the values and convert to a tuple
            A_  :       List[Any]										=  []

            for name in signature_names:
              if name != "kwargs":
                list_input.append(signature[name].default  )

            for index, value in sorted_tuple_index_mapping:
              A_  :       Any										=  prepared_for_class[value]

            A_  :       Any										=  tuple(snake_case_  )

            # Send to model
            A_  :       List[Any]										=  model(tuple_input[:-1]  )[0]

            self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       							
        )  :       Tuple										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       							
        )  :       Optional[Any]										=  self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
          A_  :       Optional[Any]										=  type
          self.model_tester.create_and_check_model(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       							
        )  :       Tuple										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(
            snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       							
        )  :       int										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(
            snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       (
            A_							
        )						,       							
        )  :       Optional[int]										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(
            snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          A_  :       str										=  TFLayoutLMvaModel.from_pretrained(snake_case_  )
          self.assertIsNotNone(snake_case_  )





def 						UpperCAmelCase__		(     ):






  """simple docstring"""





  A_  :       List[Any]										=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
  return image





@require_tf
class  _UpperCAmelCase  (   unittest.TestCase		):



      '''simple docstring'''

      @cached_property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return LayoutLMvaImageProcessor(apply_ocr=snake_case_  ) if is_vision_available() else None

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       List[str]										=  TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'  )

        A_  :       List[str]										=  self.default_image_processor
        A_  :       Optional[int]										=  prepare_img()
        A_  :       Any										=  image_processor(images=snake_case_					,      return_tensors='tf'  ).pixel_values

        A_  :       Optional[Any]										=  tf.constant([[1, 2]]  )
        A_  :       Optional[int]										=  tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]  )					,      axis=0  )

        # forward pass
        A_  :       List[str]										=  model(input_ids=snake_case_					,      bbox=snake_case_					,      pixel_values=snake_case_					,      training=snake_case_  )

        # verify the logits
        A_  :       List[Any]										=  (1, 1_9_9, 7_6_8)
        self.assertEqual(outputs.last_hidden_state.shape					,      snake_case_  )

        A_  :       Any										=  tf.constant(
            [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]  )

        self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]					,      snake_case_					,      atol=1E-4  )  )

from typing import Dict, Optional

import numpy as np

import datasets


SCREAMING_SNAKE_CASE							:List[Any]							 =				'\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'

SCREAMING_SNAKE_CASE							:List[str]							 =				'\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'

SCREAMING_SNAKE_CASE							:str							 =				'\\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			(	a_		,   a_		,   a_		,   a_		,   a_ = None		,   a_ = False		,   )		->	Tuple:







				"""simple docstring"""



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

    # turn into Numpy arrays
				__A   			= np.array(a_						)
				__A   			= np.array(a_						)

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

				__A   			= label != ignore_index
				__A   			= np.not_equal(a_		,   a_						)
				__A   			= pred_label[mask]
				__A   			= np.array(a_						)[mask]

				__A   			= pred_label[pred_label == label]

				__A   			= np.histogram(a_		,   bins=a_		,   range=(0, num_labels - 1)						)[0]
				__A   			= np.histogram(a_		,   bins=a_		,   range=(0, num_labels - 1)						)[0]
				__A   			= np.histogram(a_		,   bins=a_		,   range=(0, num_labels - 1)						)[0]

				__A   			= area_pred_label + area_label - area_intersect

				return area_intersect, area_union, area_pred_label, area_label


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_		,   a_ = None		,   a_ = False		,   )		->	Union[str, Any]:







				"""simple docstring"""



				__A   			= np.zeros((num_labels,)		,   dtype=np.floataa						)
				__A   			= np.zeros((num_labels,)		,   dtype=np.floataa						)
				__A   			= np.zeros((num_labels,)		,   dtype=np.floataa						)
				__A   			= np.zeros((num_labels,)		,   dtype=np.floataa						)
				for result, gt_seg_map in zip(a_		,   a_						):
								__A			,							__A			,							__A			,							__A   			= 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 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_		,   a_ = None		,   a_ = None		,   a_ = False		,   )		->	str:







				"""simple docstring"""



				__A			,							__A			,							__A			,							__A   			= total_intersect_and_union(
				    a_		,   a_		,   a_		,   a_		,   a_		,   a_						)

				# compute metrics
				__A   			= {}

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

				__A   			= np.nanmean(a_						)
				__A   			= np.nanmean(a_						)
				__A   			= all_acc
				__A   			= iou
				__A   			= acc

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




	'''simple docstring'''





	def 				UpperCamelCase_  (       self					: List[Any] ):
					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 				UpperCamelCase_  (       self					: int							,A					: Optional[Any]							,A					: Optional[Any]							,A					: int							,A					: bool							,A					: Optional[int] = None							,A					: Optional[Dict[int, int]] = None							,A					: bool = False							,):
					__A   			= 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
