
"""simple docstring"""






from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


lowerCamelCase__ :       List[str]						     =			logging.get_logger(__name__)




class 				lowercase__(				_UpperCAmelCase   ):
	'''simple docstring'''

	UpperCamelCase				=  ["""pixel_values"""]





	def __init__(						self    :Dict		, lowerCamelCase_    :bool = True		, lowerCamelCase_    :Dict[str, int] = None		, lowerCamelCase_    :PILImageResampling = PILImageResampling.BICUBIC		, lowerCamelCase_    :bool = True		, lowerCamelCase_    :Dict[str, int] = None		, lowerCamelCase_    :bool = True		, lowerCamelCase_    :Union[int, float] = 1 / 2_55		, lowerCamelCase_    :bool = True		, lowerCamelCase_    :Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN		, lowerCamelCase_    :Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD		, **lowerCamelCase_    :Tuple		, )							->			None:







			'''simple docstring'''




			super().__init__(**lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     str				= size if size is not None else {'''shortest_edge''': 2_24}
			SCREAMING_SNAKE_CASE       :     Optional[int]				= get_size_dict(lowerCamelCase_		, default_to_square=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
			SCREAMING_SNAKE_CASE       :     Dict				= get_size_dict(lowerCamelCase_		, param_name='''crop_size'''					)

			SCREAMING_SNAKE_CASE       :     List[str]				= do_resize
			SCREAMING_SNAKE_CASE       :     Tuple				= size
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= resample
			SCREAMING_SNAKE_CASE       :     Any				= do_center_crop
			SCREAMING_SNAKE_CASE       :     List[str]				= crop_size
			SCREAMING_SNAKE_CASE       :     int				= do_rescale
			SCREAMING_SNAKE_CASE       :     Any				= rescale_factor
			SCREAMING_SNAKE_CASE       :     str				= do_normalize
			SCREAMING_SNAKE_CASE       :     List[str]				= image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= image_std if image_std is not None else IMAGENET_DEFAULT_STD





	def   __lowerCAmelCase (						self    :List[str]		, lowerCamelCase_    :np.ndarray		, lowerCamelCase_    :Dict[str, int]		, lowerCamelCase_    :PILImageResampling = PILImageResampling.BICUBIC		, lowerCamelCase_    :Optional[Union[str, ChannelDimension]] = None		, **lowerCamelCase_    :Any		, )							->			np.ndarray:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= get_size_dict(lowerCamelCase_		, default_to_square=lowerCamelCase_					)
			# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
			if "shortest_edge" in size:
					SCREAMING_SNAKE_CASE       :     str				= int((2_56 / 2_24) * size['''shortest_edge''']					)
					SCREAMING_SNAKE_CASE       :     Any				= get_resize_output_image_size(lowerCamelCase_		, size=lowerCamelCase_		, default_to_square=lowerCamelCase_					)
					SCREAMING_SNAKE_CASE       :     Optional[int]				= {'''height''': output_size[0], '''width''': output_size[1]}
			if "height" not in size_dict or "width" not in size_dict:
					raise ValueError(
					    f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"					)
			return resize(
			    lowerCamelCase_		, size=(size_dict['''height'''], size_dict['''width'''])		, resample=lowerCamelCase_		, data_format=lowerCamelCase_		, **lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Tuple		, lowerCamelCase_    :np.ndarray		, lowerCamelCase_    :Dict[str, int]		, lowerCamelCase_    :Optional[Union[str, ChannelDimension]] = None		, **lowerCamelCase_    :int		, )							->			np.ndarray:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= get_size_dict(lowerCamelCase_					)
			if "height" not in size or "width" not in size:
					raise ValueError(f"Size dict must have keys 'height' and 'width'. Got {size.keys()}"					)
			return center_crop(lowerCamelCase_		, size=(size['''height'''], size['''width'''])		, data_format=lowerCamelCase_		, **lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Optional[Any]		, lowerCamelCase_    :np.ndarray		, lowerCamelCase_    :Union[int, float]		, lowerCamelCase_    :Optional[Union[str, ChannelDimension]] = None		, **lowerCamelCase_    :Any		, )							->			np.ndarray:







			'''simple docstring'''




			return rescale(lowerCamelCase_		, scale=lowerCamelCase_		, data_format=lowerCamelCase_		, **lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Optional[int]		, lowerCamelCase_    :np.ndarray		, lowerCamelCase_    :Union[float, List[float]]		, lowerCamelCase_    :Union[float, List[float]]		, lowerCamelCase_    :Optional[Union[str, ChannelDimension]] = None		, **lowerCamelCase_    :str		, )							->			np.ndarray:







			'''simple docstring'''




			return normalize(lowerCamelCase_		, mean=lowerCamelCase_		, std=lowerCamelCase_		, data_format=lowerCamelCase_		, **lowerCamelCase_					)







	def   __lowerCAmelCase (						self    :Union[str, Any]		, lowerCamelCase_    :ImageInput		, lowerCamelCase_    :Optional[bool] = None		, lowerCamelCase_    :Optional[Dict[str, int]] = None		, lowerCamelCase_    :PILImageResampling = None		, lowerCamelCase_    :Optional[bool] = None		, lowerCamelCase_    :Optional[Dict[str, int]] = None		, lowerCamelCase_    :Optional[bool] = None		, lowerCamelCase_    :Optional[float] = None		, lowerCamelCase_    :Optional[bool] = None		, lowerCamelCase_    :Optional[Union[float, Iterable[float]]] = None		, lowerCamelCase_    :Optional[Union[float, Iterable[float]]] = None		, lowerCamelCase_    :Optional[TensorType] = None		, lowerCamelCase_    :ChannelDimension = ChannelDimension.FIRST		, **lowerCamelCase_    :Optional[int]		, )							->			BatchFeature:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= do_resize if do_resize is not None else self.do_resize
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= resample if resample is not None else self.resample
			SCREAMING_SNAKE_CASE       :     List[Any]				= do_center_crop if do_center_crop is not None else self.do_center_crop
			SCREAMING_SNAKE_CASE       :     Dict				= do_rescale if do_rescale is not None else self.do_rescale
			SCREAMING_SNAKE_CASE       :     Optional[int]				= rescale_factor if rescale_factor is not None else self.rescale_factor
			SCREAMING_SNAKE_CASE       :     Optional[int]				= do_normalize if do_normalize is not None else self.do_normalize
			SCREAMING_SNAKE_CASE       :     Dict				= image_mean if image_mean is not None else self.image_mean
			SCREAMING_SNAKE_CASE       :     List[str]				= image_std if image_std is not None else self.image_std

			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= size if size is not None else self.size
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= get_size_dict(lowerCamelCase_		, default_to_square=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     str				= crop_size if crop_size is not None else self.crop_size
			SCREAMING_SNAKE_CASE       :     List[Any]				= get_size_dict(lowerCamelCase_		, param_name='''crop_size'''					)

			SCREAMING_SNAKE_CASE       :     str				= make_list_of_images(lowerCamelCase_					)

			if not valid_images(lowerCamelCase_					):
					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:
					raise ValueError('''Size must be specified if do_resize is True.'''					)

			if do_center_crop and crop_size is None:
					raise ValueError('''Crop size must be specified if do_center_crop 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.'''					)

			# All transformations expect numpy arrays.
			SCREAMING_SNAKE_CASE       :     List[Any]				= [to_numpy_array(lowerCamelCase_					) for image in images]

			if do_resize:
					SCREAMING_SNAKE_CASE       :     Union[str, Any]				= [self.resize(lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_					) for image in images]

			if do_center_crop:
					SCREAMING_SNAKE_CASE       :     Union[str, Any]				= [self.center_crop(lowerCamelCase_		, lowerCamelCase_					) for image in images]

			if do_rescale:
					SCREAMING_SNAKE_CASE       :     Tuple				= [self.rescale(lowerCamelCase_		, lowerCamelCase_					) for image in images]

			if do_normalize:
					SCREAMING_SNAKE_CASE       :     Dict				= [self.normalize(lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_					) for image in images]

			SCREAMING_SNAKE_CASE       :     List[str]				= [to_channel_dimension_format(lowerCamelCase_		, lowerCamelCase_					) for image in images]

			SCREAMING_SNAKE_CASE       :     Any				= {'''pixel_values''': images}
			return BatchFeature(data=lowerCamelCase_		, tensor_type=lowerCamelCase_					)







"""simple docstring"""






from sklearn.metrics import fa_score

import datasets


lowerCamelCase__ :       List[Any]						     =			"\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"


lowerCamelCase__ :       str						     =			"\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"


lowerCamelCase__ :       int						     =			"\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 				lowercase__(				datasets.Metric   ):
	'''simple docstring'''

	def   __lowerCAmelCase (						self    :str					)							->			Any:







			'''simple docstring'''




			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   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :int=None		, lowerCamelCase_    :str=1		, lowerCamelCase_    :Union[str, Any]="binary"		, lowerCamelCase_    :Dict=None					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= fa_score(
			    lowerCamelCase_		, lowerCamelCase_		, labels=lowerCamelCase_		, pos_label=lowerCamelCase_		, average=lowerCamelCase_		, sample_weight=lowerCamelCase_					)
			return {"f1": float(lowerCamelCase_					) if score.size == 1 else score}





