


from sklearn.metrics import fa_score

import datasets


SCREAMING_SNAKE_CASE__     					=			"\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n"


SCREAMING_SNAKE_CASE__     					=			"\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {'f1': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results['f1'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(round(results['f1'], 2))\n        0.35\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n        >>> print(round(results['f1'], 2))\n        0.33\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'f1': array([0.8, 0. , 0. ])}\n"


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



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






		def _snake_case		(						self				:     Tuple):
				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.f1_score.html"]   ,  )







		def _snake_case		(						self				:     List[str]   ,  UpperCAmelCase				:     str   ,  UpperCAmelCase				:     Union[str, Any]   ,  UpperCAmelCase				:     List[str]=None   ,  UpperCAmelCase				:     Optional[Any]=1   ,  UpperCAmelCase				:     str="binary"   ,  UpperCAmelCase				:     str=None):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						fa_score(
				    UpperCAmelCase   ,  UpperCAmelCase   ,  labels=UpperCAmelCase   ,  pos_label=UpperCAmelCase   ,  average=UpperCAmelCase   ,  sample_weight=UpperCAmelCase)
				return {"f1": float(UpperCAmelCase) if score.size == 1 else score}










from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


SCREAMING_SNAKE_CASE__     					=			logging.get_logger(__name__)



class 						_UpperCAmelCase      (     lowercase							):
		lowerCamelCase_	:			Dict       			=  ["""pixel_values"""]






		def __init__(						self				:     Tuple   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     Dict[str, int] = None   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BICUBIC   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     Union[int, float] = 1 / 2_55   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     Optional[Union[float, List[float]]] = None   ,  UpperCAmelCase				:     Optional[Union[float, List[float]]] = None   ,  UpperCAmelCase				:     bool = True   ,  **UpperCAmelCase				:     Any   ,  ):
				super().__init__(**UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						size if size is not None else {"height": 3_84, "width": 3_84}
				SCREAMING_SNAKE_CASE_				:str				     =						get_size_dict(UpperCAmelCase   ,  default_to_square=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						do_resize
				SCREAMING_SNAKE_CASE_				:int				     =						size
				SCREAMING_SNAKE_CASE_				:int				     =						resample
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						do_rescale
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						rescale_factor
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						do_normalize
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						image_mean if image_mean is not None else OPENAI_CLIP_MEAN
				SCREAMING_SNAKE_CASE_				:Dict				     =						image_std if image_std is not None else OPENAI_CLIP_STD
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						do_convert_rgb






		def _snake_case		(						self				:     int   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Dict[str, int]   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BICUBIC   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  **UpperCAmelCase				:     Any   ,  ):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						get_size_dict(UpperCAmelCase   ,  default_to_square=UpperCAmelCase)
				if "height" not in size or "width" not in size:
						raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						(size["height"], size["width"])
				return resize(UpperCAmelCase   ,  size=UpperCAmelCase   ,  resample=UpperCAmelCase   ,  data_format=UpperCAmelCase   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Optional[Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Union[int, float]   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  **UpperCAmelCase				:     List[str]   ,  ):
				return rescale(UpperCAmelCase   ,  scale=UpperCAmelCase   ,  data_format=UpperCAmelCase   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Optional[Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Union[float, List[float]]   ,  UpperCAmelCase				:     Union[float, List[float]]   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  **UpperCAmelCase				:     Optional[Any]   ,  ):
				return normalize(UpperCAmelCase   ,  mean=UpperCAmelCase   ,  std=UpperCAmelCase   ,  data_format=UpperCAmelCase   ,  **UpperCAmelCase)







		def _snake_case		(						self				:     List[Any]   ,  UpperCAmelCase				:     ImageInput   ,  UpperCAmelCase				:     Optional[bool] = None   ,  UpperCAmelCase				:     Optional[Dict[str, int]] = None   ,  UpperCAmelCase				:     PILImageResampling = None   ,  UpperCAmelCase				:     Optional[bool] = None   ,  UpperCAmelCase				:     Optional[float] = None   ,  UpperCAmelCase				:     Optional[bool] = None   ,  UpperCAmelCase				:     Optional[Union[float, List[float]]] = None   ,  UpperCAmelCase				:     Optional[Union[float, List[float]]] = None   ,  UpperCAmelCase				:     Optional[Union[str, TensorType]] = None   ,  UpperCAmelCase				:     bool = None   ,  UpperCAmelCase				:     ChannelDimension = ChannelDimension.FIRST   ,  **UpperCAmelCase				:     Dict   ,  ):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						do_resize if do_resize is not None else self.do_resize
				SCREAMING_SNAKE_CASE_				:Tuple				     =						resample if resample is not None else self.resample
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						do_rescale if do_rescale is not None else self.do_rescale
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						rescale_factor if rescale_factor is not None else self.rescale_factor
				SCREAMING_SNAKE_CASE_				:Dict				     =						do_normalize if do_normalize is not None else self.do_normalize
				SCREAMING_SNAKE_CASE_				:List[str]				     =						image_mean if image_mean is not None else self.image_mean
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						image_std if image_std is not None else self.image_std
				SCREAMING_SNAKE_CASE_				:Tuple				     =						do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

				SCREAMING_SNAKE_CASE_				:Dict				     =						size if size is not None else self.size
				SCREAMING_SNAKE_CASE_				:Tuple				     =						get_size_dict(UpperCAmelCase   ,  default_to_square=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Tuple				     =						make_list_of_images(UpperCAmelCase)

				if not valid_images(UpperCAmelCase):
						raise ValueError(
						    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
						    "torch.Tensor, tf.Tensor or jax.ndarray.")

				if do_resize and size is None or resample is None:
						raise ValueError("Size and resample must be specified if do_resize is True.")

				if do_rescale and rescale_factor is None:
						raise ValueError("Rescale factor must be specified if do_rescale is True.")

				if do_normalize and (image_mean is None or image_std is None):
						raise ValueError("Image mean and std must be specified if do_normalize is True.")

				# PIL RGBA images are converted to RGB
				if do_convert_rgb:
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						[convert_to_rgb(UpperCAmelCase) for image in images]

				# All transformations expect numpy arrays.
				SCREAMING_SNAKE_CASE_				:List[str]				     =						[to_numpy_array(UpperCAmelCase) for image in images]

				if do_resize:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						[self.resize(image=UpperCAmelCase   ,  size=UpperCAmelCase   ,  resample=UpperCAmelCase) for image in images]

				if do_rescale:
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						[self.rescale(image=UpperCAmelCase   ,  scale=UpperCAmelCase) for image in images]

				if do_normalize:
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						[self.normalize(image=UpperCAmelCase   ,  mean=UpperCAmelCase   ,  std=UpperCAmelCase) for image in images]

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						[to_channel_dimension_format(UpperCAmelCase   ,  UpperCAmelCase) for image in images]

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						BatchFeature(data={"pixel_values": images}   ,  tensor_type=UpperCAmelCase)

				return encoded_outputs






