






'''simple docstring'''




from typing import Dict, Optional

import numpy as np

import datasets


lowerCAmelCase__          =						'\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n'

lowerCAmelCase__          =						'\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric("mean_iou")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), \'per_category_accuracy\': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n'

lowerCAmelCase__          =						'\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}'







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_ = None     ,      lowerCamelCase_ = False     ,      )							->     Union[str, Any]:
		if label_map is not None:
				for old_id, new_id in label_map.items():
						UpperCamelCase__				:					Optional[Any]					=					new_id

    # turn into Numpy arrays
		UpperCamelCase__				:					str					=					np.array(lowerCamelCase_)
		UpperCamelCase__				:					Dict					=					np.array(lowerCamelCase_)

		if reduce_labels:
				UpperCamelCase__				:					List[str]					=					255
				UpperCamelCase__				:					Union[str, Any]					=					label - 1
				UpperCamelCase__				:					Optional[Any]					=					255

		UpperCamelCase__				:					Dict					=					label != ignore_index
		UpperCamelCase__				:					List[Any]					=					np.not_equal(lowerCamelCase_     ,      lowerCamelCase_)
		UpperCamelCase__				:					int					=					pred_label[mask]
		UpperCamelCase__				:					Optional[Any]					=					np.array(lowerCamelCase_)[mask]

		UpperCamelCase__				:					Union[str, Any]					=					pred_label[pred_label == label]

		UpperCamelCase__				:					int					=					np.histogram(lowerCamelCase_     ,      bins=lowerCamelCase_     ,      range=(0, num_labels - 1))[0]
		UpperCamelCase__				:					Optional[int]					=					np.histogram(lowerCamelCase_     ,      bins=lowerCamelCase_     ,      range=(0, num_labels - 1))[0]
		UpperCamelCase__				:					Optional[int]					=					np.histogram(lowerCamelCase_     ,      bins=lowerCamelCase_     ,      range=(0, num_labels - 1))[0]

		UpperCamelCase__				:					int					=					area_pred_label + area_label - area_intersect

		return area_intersect, area_union, area_pred_label, area_label







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

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

		UpperCamelCase__				:					List[Any]					=					total_area_intersect.sum() / total_area_label.sum()
		UpperCamelCase__				:					Tuple					=					total_area_intersect / total_area_union
		UpperCamelCase__				:					str					=					total_area_intersect / total_area_label

		UpperCamelCase__				:					Union[str, Any]					=					np.nanmean(lowerCamelCase_)
		UpperCamelCase__				:					List[Any]					=					np.nanmean(lowerCamelCase_)
		UpperCamelCase__				:					Any					=					all_acc
		UpperCamelCase__				:					Optional[int]					=					iou
		UpperCamelCase__				:					Union[str, Any]					=					acc

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

		return metrics







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

	def      __UpperCamelCase							(      self   :						Optional[int]):
			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   :						Union[str, Any]  ,					UpperCAmelCase_   :						Optional[int]  ,					UpperCAmelCase_   :						Any  ,					UpperCAmelCase_   :						int  ,					UpperCAmelCase_   :						bool  ,					UpperCAmelCase_   :						Optional[int] = None  ,					UpperCAmelCase_   :						Optional[Dict[int, int]] = None  ,					UpperCAmelCase_   :						bool = False  ,					):
			UpperCamelCase__				:					Tuple					=					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 argparse
import struct
import unittest







class       __lowercase					:

	def __init__(      self   :						Tuple  ,					UpperCAmelCase_   :						bytes):
			UpperCamelCase__				:					Dict					=					data

			# Initialize hash values
			UpperCamelCase__				:					Any					=					[
			    0X6A_09E_667,
			    0XBB_67A_E85,
			    0X3C_6EF_372,
			    0XA5_4FF_53A,
			    0X51_0E5_27F,
			    0X9B_056_88C,
			    0X1F_83D_9AB,
			    0X5B_E0C_D19,
			]

			# Initialize round constants
			UpperCamelCase__				:					List[Any]					=					[
			    0X42_8A2_F98,
			    0X71_374_491,
			    0XB5_C0F_BCF,
			    0XE9_B5D_BA5,
			    0X39_56C_25B,
			    0X59_F11_1F1,
			    0X92_3F8_2A4,
			    0XAB_1C5_ED5,
			    0XD8_07A_A98,
			    0X12_835_B01,
			    0X24_318_5BE,
			    0X55_0C7_DC3,
			    0X72_BE5_D74,
			    0X80_DEB_1FE,
			    0X9B_DC0_6A7,
			    0XC1_9BF_174,
			    0XE4_9B6_9C1,
			    0XEF_BE4_786,
			    0X0F_C19_DC6,
			    0X24_0CA_1CC,
			    0X2D_E92_C6F,
			    0X4A_748_4AA,
			    0X5C_B0A_9DC,
			    0X76_F98_8DA,
			    0X98_3E5_152,
			    0XA8_31C_66D,
			    0XB0_032_7C8,
			    0XBF_597_FC7,
			    0XC6_E00_BF3,
			    0XD5_A79_147,
			    0X06_CA6_351,
			    0X14_292_967,
			    0X27_B70_A85,
			    0X2E_1B2_138,
			    0X4D_2C6_DFC,
			    0X53_380_D13,
			    0X65_0A7_354,
			    0X76_6A0_ABB,
			    0X81_C2C_92E,
			    0X92_722_C85,
			    0XA2_BFE_8A1,
			    0XA8_1A6_64B,
			    0XC2_4B8_B70,
			    0XC7_6C5_1A3,
			    0XD1_92E_819,
			    0XD6_990_624,
			    0XF4_0E3_585,
			    0X10_6AA_070,
			    0X19_A4C_116,
			    0X1E_376_C08,
			    0X27_487_74C,
			    0X34_B0B_CB5,
			    0X39_1C0_CB3,
			    0X4E_D8A_A4A,
			    0X5B_9CC_A4F,
			    0X68_2E6_FF3,
			    0X74_8F8_2EE,
			    0X78_A56_36F,
			    0X84_C87_814,
			    0X8C_C70_208,
			    0X90_BEF_FFA,
			    0XA4_506_CEB,
			    0XBE_F9A_3F7,
			    0XC6_717_8F2,
			]

			UpperCamelCase__				:					Tuple					=					self.preprocessing(self.data)
			self.final_hash()

	@staticmethod
	def      __UpperCamelCase							(      UpperCAmelCase_   :						bytes):
			UpperCamelCase__				:					List[Any]					=					B'\x80' + (B'\x00' * (63 - (len(UpperCAmelCase_) + 8) % 64))
			UpperCamelCase__				:					List[Any]					=					struct.pack('>Q'  ,					(len(UpperCAmelCase_) * 8))
			return data + padding + big_endian_integer

	def      __UpperCamelCase							(      self   :						Union[str, Any]):
			# Convert into blocks of 64 bytes
			UpperCamelCase__				:					int					=					[
			    self.preprocessed_data[x : x + 64]
			    for x in range(0  ,					len(self.preprocessed_data)  ,					64)
			]

			for block in self.blocks:
					# Convert the given block into a list of 4 byte integers
					UpperCamelCase__				:					Tuple					=					list(struct.unpack('>16L'  ,					UpperCAmelCase_))
					# add 48 0-ed integers
					words += [0] * 48

					UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__				:					str					=					self.hashes

					for index in range(0  ,					64):
							if index > 15:
									# modify the zero-ed indexes at the end of the array
									UpperCamelCase__				:					Dict					=					(
									    self.ror(words[index - 15]  ,					7)
									    ^ self.ror(words[index - 15]  ,					18)
									    ^ (words[index - 15] >> 3)
									)
									UpperCamelCase__				:					Tuple					=					(
									    self.ror(words[index - 2]  ,					17)
									    ^ self.ror(words[index - 2]  ,					19)
									    ^ (words[index - 2] >> 10)
									)

									UpperCamelCase__				:					int					=					(
									    words[index - 16] + sa + words[index - 7] + sa
									) % 0X100_000_000

							# Compression
							UpperCamelCase__				:					Optional[Any]					=					self.ror(UpperCAmelCase_  ,					6) ^ self.ror(UpperCAmelCase_  ,					11) ^ self.ror(UpperCAmelCase_  ,					25)
							UpperCamelCase__				:					List[str]					=					(e & f) ^ ((~e & 0XFF_FFF_FFF) & g)
							UpperCamelCase__				:					List[Any]					=					(
							    h + sa + ch + self.round_constants[index] + words[index]
							) % 0X100_000_000
							UpperCamelCase__				:					List[str]					=					self.ror(UpperCAmelCase_  ,					2) ^ self.ror(UpperCAmelCase_  ,					13) ^ self.ror(UpperCAmelCase_  ,					22)
							UpperCamelCase__				:					Dict					=					(a & b) ^ (a & c) ^ (b & c)
							UpperCamelCase__				:					List[str]					=					(sa + maj) % 0X100_000_000

							UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__				:					Tuple					=					(
							    g,
							    f,
							    e,
							    ((d + tempa) % 0X100_000_000),
							    c,
							    b,
							    a,
							    ((tempa + tempa) % 0X100_000_000),
							)

					UpperCamelCase__				:					List[Any]					=					[a, b, c, d, e, f, g, h]

					# Modify final values
					UpperCamelCase__				:					Optional[Any]					=					[
					    ((element + mutated_hash_values[index]) % 0X100_000_000)
					    for index, element in enumerate(self.hashes)
					]

			UpperCamelCase__				:					Any					=					''.join([hex(UpperCAmelCase_)[2:].zfill(8) for value in self.hashes])





	def      __UpperCamelCase							(      self   :						int  ,					UpperCAmelCase_   :						int  ,					UpperCAmelCase_   :						int):
			return 0XFF_FFF_FFF & (value << (32 - rotations)) | (value >> rotations)







class       __lowercase					(unittest.TestCase    ):

	def      __UpperCamelCase							(      self   :						int):
			import hashlib

			UpperCamelCase__				:					str					=					bytes('Test String'  ,					'utf-8')
			self.assertEqual(SHAaaa(UpperCAmelCase_).hash  ,					hashlib.shaaaa(UpperCAmelCase_).hexdigest())







def       __UpperCAmelCase						(  )							->     None:
		import doctest

		doctest.testmod()

		UpperCamelCase__				:					Union[str, Any]					=					argparse.ArgumentParser()
		parser.add_argument(
		    '-s'     ,      '--string'     ,      dest='input_string'     ,      default='Hello World!! Welcome to Cryptography'     ,      help='Hash the string'     ,      )
		parser.add_argument(
		    '-f'     ,      '--file'     ,      dest='input_file'     ,      help='Hash contents of a file')

		UpperCamelCase__				:					List[str]					=					parser.parse_args()

		UpperCamelCase__				:					str					=					args.input_string

		# hash input should be a bytestring
		if args.input_file:
				with open(args.input_file     ,      'rb') as f:
						UpperCamelCase__				:					Any					=					f.read()
		else:
				UpperCamelCase__				:					List[Any]					=					bytes(lowerCamelCase_     ,      'utf-8')

		print(SHAaaa(lowerCamelCase_).hash)


if __name__ == "__main__":
		main()




