



import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import TvltImageProcessor





def     __lowerCamelCase							(   __magic_name__						:	Optional[Any]  ,			__magic_name__						:	List[Any]=10  ,			__magic_name__						:	Union[str, Any]=10  ,			__magic_name__						:	Tuple=False  ,			__magic_name__						:	str=False    ):
							a__:							Any									=[]
							for i in range(image_processor_tester.num_frames    ):
														video.append(np.random.randint(255  ,			size=(image_processor_tester.num_channels, width, height)  ,			dtype=np.uinta    )    )

							if not numpify and not torchify:
														# PIL expects the channel dimension as last dimension
														a__:							Optional[Any]									=[Image.fromarray(np.moveaxis(_UpperCAmelCase  ,			0  ,			-1    )    ) for frame in video]

							if torchify:
														a__:							Any									=[torch.from_numpy(_UpperCAmelCase    ) for frame in video]

							return video





def     __lowerCamelCase							(   __magic_name__						:	Any  ,			__magic_name__						:	Optional[Any]=False  ,			__magic_name__						:	Optional[Any]=False  ,			__magic_name__						:	str=False    ):
							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							a__:							Dict									=[]
							for i in range(image_processor_tester.batch_size    ):
														if equal_resolution:
																					a__:							Tuple									=image_processor_tester.max_resolution
														else:
																					a__				,      a__:							str									=np.random.choice(
																					    np.arange(image_processor_tester.min_resolution  ,			image_processor_tester.max_resolution    )  ,			2    )
																					a__:							str									=prepare_video(
																					    image_processor_tester=_UpperCAmelCase  ,			width=_UpperCAmelCase  ,			height=_UpperCAmelCase  ,			numpify=_UpperCAmelCase  ,			torchify=_UpperCAmelCase  ,			)
														video_inputs.append(_UpperCAmelCase    )

							return video_inputs


class 						lowerCamelCase__			(		unittest.TestCase ):


						def __init__(			self    :	Any   ,							_a    :	Optional[int]   ,							_a    :	Dict=7   ,							_a    :	int=3   ,							_a    :	int=4   ,							_a    :	int=1_8   ,							_a    :	Dict=3_0   ,							_a    :	Dict=4_0_0   ,							_a    :	Tuple=True   ,							_a    :	Dict=None   ,							_a    :	Any=True   ,							_a    :	Union[str, Any]=[0.5, 0.5, 0.5]   ,							_a    :	List[Any]=[0.5, 0.5, 0.5]   ,							_a    :	Optional[Any]=True   ,							_a    :	Optional[Any]=None   ,							):
													a__:							List[Any]									=size if size is not None else {"shortest_edge": 1_8}
													a__:							Tuple									=crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}

													a__:							Optional[Any]									=parent
													a__:							Tuple									=batch_size
													a__:							int									=num_channels
													a__:							List[Any]									=num_frames
													a__:							Any									=image_size
													a__:							Any									=min_resolution
													a__:							List[str]									=max_resolution
													a__:							str									=do_resize
													a__:							Any									=size
													a__:							Union[str, Any]									=do_normalize
													a__:							Optional[int]									=image_mean
													a__:							Union[str, Any]									=image_std
													a__:							Union[str, Any]									=do_center_crop
													a__:							Union[str, Any]									=crop_size







						def 	_lowerCamelCase      (			self    :	Union[str, Any]      ):
													return {
													    "image_mean": self.image_mean,
													    "image_std": self.image_std,
													    "do_normalize": self.do_normalize,
													    "do_resize": self.do_resize,
													    "size": self.size,
													    "do_center_crop": self.do_center_crop,
													    "crop_size": self.crop_size,
													}


@require_torch
@require_vision
class 						lowerCamelCase__			(		_a					,       unittest.TestCase ):
						_lowerCAmelCase             =			TvltImageProcessor if is_vision_available() else None


						def 	_lowerCamelCase      (			self    :	Dict      ):
													a__:							List[str]									=TvltImageProcessorTester(self      )


						@property
						def 	_lowerCamelCase      (			self    :	Optional[int]      ):
													return self.image_processor_tester.prepare_image_processor_dict()


						def 	_lowerCamelCase      (			self    :	Union[str, Any]      ):
													a__:							Optional[int]									=self.image_processing_class(**self.image_processor_dict      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"image_mean"      )      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"image_std"      )      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"do_normalize"      )      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"do_resize"      )      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"do_center_crop"      )      )
													self.assertTrue(hasattr(UpperCAmelCase_   ,							"size"      )      )


						def 	_lowerCamelCase      (			self    :	Tuple      ):
													# Initialize image_processor
													a__:							Tuple									=self.image_processing_class(**self.image_processor_dict      )
													# create random PIL videos
													a__:							List[Any]									=prepare_video_inputs(self.image_processor_tester   ,							equal_resolution=UpperCAmelCase_      )
													for video in video_inputs:
																				self.assertIsInstance(UpperCAmelCase_   ,							UpperCAmelCase_      )
																				self.assertIsInstance(video[0]   ,							Image.Image      )

													# Test not batched input
													a__:							List[Any]									=image_processor(video_inputs[0]   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        1,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)

													# Test batched
													a__:							Union[str, Any]									=image_processor(UpperCAmelCase_   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)


						def 	_lowerCamelCase      (			self    :	str      ):
													# Initialize image_processor
													a__:							Union[str, Any]									=self.image_processing_class(**self.image_processor_dict      )
													# create random numpy tensors
													a__:							Tuple									=prepare_video_inputs(self.image_processor_tester   ,							equal_resolution=UpperCAmelCase_   ,							numpify=UpperCAmelCase_      )
													for video in video_inputs:
																				self.assertIsInstance(UpperCAmelCase_   ,							UpperCAmelCase_      )
																				self.assertIsInstance(video[0]   ,							np.ndarray      )

													# Test not batched input
													a__:							int									=image_processor(video_inputs[0]   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        1,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)

													# Test batched
													a__:							Any									=image_processor(UpperCAmelCase_   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)







						def 	_lowerCamelCase      (			self    :	Any      ):
													# Initialize image_processor
													a__:							Union[str, Any]									=self.image_processing_class(**self.image_processor_dict      )
													# create random PyTorch tensors
													a__:							Optional[int]									=prepare_video_inputs(self.image_processor_tester   ,							equal_resolution=UpperCAmelCase_   ,							torchify=UpperCAmelCase_      )
													for video in video_inputs:
																				self.assertIsInstance(UpperCAmelCase_   ,							UpperCAmelCase_      )
																				self.assertIsInstance(video[0]   ,							torch.Tensor      )

													# Test not batched input
													a__:							Dict									=image_processor(video_inputs[0]   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        1,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)

													# Test batched
													a__:							int									=image_processor(UpperCAmelCase_   ,							return_tensors="pt"      ).pixel_values
													self.assertEqual(
													    encoded_videos.shape   ,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_frames,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size["height"],
													        self.image_processor_tester.crop_size["width"],
													    )   ,							)












from sklearn.metrics import accuracy_score

import datasets


UpperCAmelCase__    :      Optional[Any]       					='''
Accuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
 Where:
TP: True positive
TN: True negative
FP: False positive
FN: False negative
'''


UpperCAmelCase__    :      Optional[int]       					='''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.

Examples:

    Example 1-A simple example
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])
        >>> print(results)
        {\'accuracy\': 0.5}

    Example 2-The same as Example 1, except with `normalize` set to `False`.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)
        >>> print(results)
        {\'accuracy\': 3.0}

    Example 3-The same as Example 1, except with `sample_weight` set.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])
        >>> print(results)
        {\'accuracy\': 0.8778625954198473}
'''


UpperCAmelCase__    :      List[str]       					='''
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
'''

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


				def _snake_case							(		self				):
								return datasets.MetricInfo(
								    description=_DESCRIPTION ,			citation=_CITATION ,			inputs_description=_KWARGS_DESCRIPTION ,			features=datasets.Features(
								        {
								            """predictions""": datasets.Sequence(datasets.Value("""int32"""				)				),
								            """references""": datasets.Sequence(datasets.Value("""int32"""				)				),
								        }
								        if self.config_name == """multilabel"""
								        else {
								            """predictions""": datasets.Value("""int32"""				),
								            """references""": datasets.Value("""int32"""				),
								        }				) ,			reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"""] ,			)


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_=True ,			UpperCAmelCase_=None				):
								return {
								    "accuracy": float(
								        accuracy_score(UpperCAmelCase_ ,			UpperCAmelCase_ ,			normalize=UpperCAmelCase_ ,			sample_weight=UpperCAmelCase_				)				)
								}





