

'''simple docstring'''





from typing import Dict, Optional

import numpy as np

import datasets


UpperCamelCase_    						=       """
IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union
between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,
the mean IoU of the image is calculated by taking the IoU of each class and averaging them.
"""

UpperCamelCase_    						=       """
Args:
    predictions (`List[ndarray]`):
        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    references (`List[ndarray]`):
        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    num_labels (`int`):
        Number of classes (categories).
    ignore_index (`int`):
        Index that will be ignored during evaluation.
    nan_to_num (`int`, *optional*):
        If specified, NaN values will be replaced by the number defined by the user.
    label_map (`dict`, *optional*):
        If specified, dictionary mapping old label indices to new label indices.
    reduce_labels (`bool`, *optional*, defaults to `False`):
        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,
        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.

Returns:
    `Dict[str, float | ndarray]` comprising various elements:
    - *mean_iou* (`float`):
        Mean Intersection-over-Union (IoU averaged over all categories).
    - *mean_accuracy* (`float`):
        Mean accuracy (averaged over all categories).
    - *overall_accuracy* (`float`):
        Overall accuracy on all images.
    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):
        Per category accuracy.
    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):
        Per category IoU.

Examples:

    >>> import numpy as np

    >>> mean_iou = datasets.load_metric(\"mean_iou\")

    >>> # suppose one has 3 different segmentation maps predicted
    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])
    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])

    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])
    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])

    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])
    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])

    >>> predicted = [predicted_1, predicted_2, predicted_3]
    >>> ground_truth = [actual_1, actual_2, actual_3]

    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'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.        ])}
"""

UpperCamelCase_    						=       """\
@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,
author = {{MMSegmentation Contributors}},
license = {Apache-2.0},
month = {7},
title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},
url = {https://github.com/open-mmlab/mmsegmentation},
year = {2020}
}"""






def 				_lowerCAmelCase			(   __magic_name__						:     Union[str, Any]   , __magic_name__						:     List[Any]   , __magic_name__						:     int   , __magic_name__						:     bool   , __magic_name__						:     Optional[Dict[int, int]] = None   , __magic_name__						:     bool = False   , )				->  Optional[Any]:
						if label_map is not None:
												for old_id, new_id in label_map.items():
																		lowercase :							Tuple    		=new_id

    # turn into Numpy arrays
						lowercase :							Any    		=np.array(__magic_name__						)
						lowercase :							Any    		=np.array(__magic_name__						)

						if reduce_labels:
												lowercase :							Optional[Any]    		=255
												lowercase :							Any    		=label - 1
												lowercase :							Optional[Any]    		=255

						lowercase :							int    		=label != ignore_index
						lowercase :							Optional[Any]    		=np.not_equal(__magic_name__   , __magic_name__						)
						lowercase :							Tuple    		=pred_label[mask]
						lowercase :							List[Any]    		=np.array(__magic_name__						)[mask]

						lowercase :							Optional[Any]    		=pred_label[pred_label == label]

						lowercase :							Any    		=np.histogram(__magic_name__   , bins=__magic_name__   , range=(0, num_labels - 1)						)[0]
						lowercase :							Any    		=np.histogram(__magic_name__   , bins=__magic_name__   , range=(0, num_labels - 1)						)[0]
						lowercase :							Dict    		=np.histogram(__magic_name__   , bins=__magic_name__   , range=(0, num_labels - 1)						)[0]

						lowercase :							Union[str, Any]    		=area_pred_label + area_label - area_intersect

						return area_intersect, area_union, area_pred_label, area_label






def 				_lowerCAmelCase			(   __magic_name__						:     str   , __magic_name__						:     List[Any]   , __magic_name__						:     str   , __magic_name__						:     bool   , __magic_name__						:     Optional[Dict[int, int]] = None   , __magic_name__						:     bool = False   , )				->  int:
						lowercase :							List[Any]    		=np.zeros((num_labels,)   , dtype=np.floataa						)
						lowercase :							Any    		=np.zeros((num_labels,)   , dtype=np.floataa						)
						lowercase :							str    		=np.zeros((num_labels,)   , dtype=np.floataa						)
						lowercase :							List[Any]    		=np.zeros((num_labels,)   , dtype=np.floataa						)
						for result, gt_seg_map in zip(__magic_name__   , __magic_name__						):
												lowercase		,	lowercase		,	lowercase		,	lowercase :							List[str]    		=intersect_and_union(
												    __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__						)
												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 				_lowerCAmelCase			(   __magic_name__						:     Optional[Any]   , __magic_name__						:     List[Any]   , __magic_name__						:     List[Any]   , __magic_name__						:     bool   , __magic_name__						:     Optional[int] = None   , __magic_name__						:     Optional[Dict[int, int]] = None   , __magic_name__						:     bool = False   , )				->  List[str]:
						lowercase		,	lowercase		,	lowercase		,	lowercase :							Optional[Any]    		=total_intersect_and_union(
						    __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__   , __magic_name__						)

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

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

						lowercase :							List[Any]    		=np.nanmean(__magic_name__						)
						lowercase :							Tuple    		=np.nanmean(__magic_name__						)
						lowercase :							Dict    		=all_acc
						lowercase :							Any    		=iou
						lowercase :							str    		=acc

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

						return metrics







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







				def  lowerCamelCase_	(       self     :		str   ):
										'''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  lowerCamelCase_	(       self     :		Optional[Any]		,					UpperCAmelCase__     :		List[str]		,					UpperCAmelCase__     :		Dict		,					UpperCAmelCase__     :		int		,					UpperCAmelCase__     :		bool		,					UpperCAmelCase__     :		Optional[int] = None		,					UpperCAmelCase__     :		Optional[Dict[int, int]] = None		,					UpperCAmelCase__     :		bool = False		,					):
										'''simple docstring'''
										lowercase :							List[Any]    		=mean_iou(
										    results=UpperCAmelCase__		,					gt_seg_maps=UpperCAmelCase__		,					num_labels=UpperCAmelCase__		,					ignore_index=UpperCAmelCase__		,					nan_to_num=UpperCAmelCase__		,					label_map=UpperCAmelCase__		,					reduce_labels=UpperCAmelCase__		,					)
										return iou_result








'''simple docstring'''





import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCamelCase_    						=       logging.getLogger(__name__)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]   , __magic_name__						:     str						)				->  Union[str, Any]:
						return (preds == labels).mean()





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    field(
				    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Pretrained config name or path if not the same as model_name'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,							)





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()      )}      )
				lowerCamelCase_		       =    field(metadata={'help': 'Should contain the data files for the task.'}      )
				lowerCamelCase_		       =    field(
				    default=1_28						,							metadata={
				        'help': (
				            'The maximum total input sequence length after tokenization. Sequences longer '
				            'than this will be truncated, sequences shorter will be padded.'
				        )
				    }						,							)
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Overwrite the cached training and evaluation sets'}      )






def 				_lowerCAmelCase			(   )				->  int:
						# See all possible arguments in src/transformers/training_args.py
						# or by passing the --help flag to this script.
						# We now keep distinct sets of args, for a cleaner separation of concerns.

						lowercase :							Dict    		=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
						lowercase		,	lowercase		,	lowercase :							List[Any]    		=parser.parse_args_into_dataclasses()

						if (
						    os.path.exists(training_args.output_dir						)
						    and os.listdir(training_args.output_dir						)
						    and training_args.do_train
						    and not training_args.overwrite_output_dir
						):
												raise ValueError(
												    f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
												    ''' --overwrite_output_dir to overcome.'''						)

						# Setup logging
						logging.basicConfig(
						    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''   , datefmt='''%m/%d/%Y %H:%M:%S'''   , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN   , )
						logger.warning(
						    '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''   , training_args.local_rank   , training_args.device   , training_args.n_gpu   , bool(training_args.local_rank != -1						)   , training_args.fpaa   , )
						# Set the verbosity to info of the Transformers logger (on main process only):
						if is_main_process(training_args.local_rank						):
												transformers.utils.logging.set_verbosity_info()
												transformers.utils.logging.enable_default_handler()
												transformers.utils.logging.enable_explicit_format()
						logger.info('''Training/evaluation parameters %s'''   , __magic_name__						)

						# Set seed
						set_seed(training_args.seed						)

						try:
												lowercase :							Any    		=processors[data_args.task_name]()
												lowercase :							Optional[int]    		=processor.get_labels()
												lowercase :							str    		=len(__magic_name__						)
						except KeyError:
												raise ValueError('''Task not found: %s''' % (data_args.task_name)						)

						# Load pretrained model and tokenizer
						#
						# Distributed training:
						# The .from_pretrained methods guarantee that only one local process can concurrently
						# download model & vocab.

						lowercase :							List[str]    		=AutoConfig.from_pretrained(
						    model_args.config_name if model_args.config_name else model_args.model_name_or_path   , num_labels=__magic_name__   , finetuning_task=data_args.task_name   , cache_dir=model_args.cache_dir   , )
						lowercase :							int    		=AutoTokenizer.from_pretrained(
						    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path   , cache_dir=model_args.cache_dir   , )
						lowercase :							Any    		=AutoModelForMultipleChoice.from_pretrained(
						    model_args.model_name_or_path   , from_tf=bool('''.ckpt''' in model_args.model_name_or_path						)   , config=__magic_name__   , cache_dir=model_args.cache_dir   , )

						# Get datasets
						lowercase :							int    		=(
						    MultipleChoiceDataset(
						        data_dir=data_args.data_dir   , tokenizer=__magic_name__   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , mode=Split.train   , )
						    if training_args.do_train
						    else None
						)
						lowercase :							Union[str, Any]    		=(
						    MultipleChoiceDataset(
						        data_dir=data_args.data_dir   , tokenizer=__magic_name__   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , mode=Split.dev   , )
						    if training_args.do_eval
						    else None
						)

						def compute_metrics(__magic_name__						:     EvalPrediction						) -> Dict:
												lowercase :							Dict    		=np.argmax(p.predictions   , axis=1						)
												return {"acc": simple_accuracy(__magic_name__   , p.label_ids						)}

						# Data collator
						lowercase :							List[str]    		=DataCollatorWithPadding(__magic_name__   , pad_to_multiple_of=8						) if training_args.fpaa else None

						# Initialize our Trainer
						lowercase :							Dict    		=Trainer(
						    model=__magic_name__   , args=__magic_name__   , train_dataset=__magic_name__   , eval_dataset=__magic_name__   , compute_metrics=__magic_name__   , data_collator=__magic_name__   , )

						# Training
						if training_args.do_train:
												trainer.train(
												    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path						) else None						)
												trainer.save_model()
												# For convenience, we also re-save the tokenizer to the same directory,
												# so that you can share your model easily on huggingface.co/models =)
												if trainer.is_world_master():
																		tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
						lowercase :							Optional[Any]    		={}
						if training_args.do_eval:
												logger.info('''*** Evaluate ***'''						)

												lowercase :							List[Any]    		=trainer.evaluate()

												lowercase :							Any    		=os.path.join(training_args.output_dir   , '''eval_results.txt'''						)
												if trainer.is_world_master():
																		with open(__magic_name__   , '''w'''						) as writer:
																								logger.info('''***** Eval results *****'''						)
																								for key, value in result.items():
																														logger.info('''  %s = %s'''   , __magic_name__   , __magic_name__						)
																														writer.write('''%s = %s\n''' % (key, value)						)

																								results.update(__magic_name__						)

						return results






def 				_lowerCAmelCase			(   __magic_name__						:     Any						)				->  Optional[Any]:
						# For xla_spawn (TPUs)
						main()


if __name__ == "__main__":
							main()





