




"""simple docstring"""

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 (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    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


a         =      logging.get_logger(__name__)


if is_vision_available():
       import PIL





class     lowercase_	(					__lowerCAmelCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Union[str, Any]				  =     ['''pixel_values''']

 def __init__(			self	:	Dict   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	Dict[str, int] = None   ,							_UpperCAmelCase	:	PILImageResampling = PILImageResampling.BICUBIC   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	Dict[str, int] = None   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	Union[int, float] = 1 / 255   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	Optional[Union[float, List[float]]] = None   ,							_UpperCAmelCase	:	Optional[Union[float, List[float]]] = None   ,							_UpperCAmelCase	:	bool = True   ,							**_UpperCAmelCase	:	Tuple   ,							):
       super().__init__(**_UpperCAmelCase		)
       _A        =       size if size is not None else {'shortest_edge': 224}
       _A        =       get_size_dict(_UpperCAmelCase   ,							default_to_square=_UpperCAmelCase		)
       _A        =       crop_size if crop_size is not None else {'height': 224, 'width': 224}
       _A        =       get_size_dict(_UpperCAmelCase   ,							default_to_square=_UpperCAmelCase   ,							param_name='crop_size'		)

       _A        =       do_resize
       _A        =       size
       _A        =       resample
       _A        =       do_center_crop
       _A        =       crop_size
       _A        =       do_rescale
       _A        =       rescale_factor
       _A        =       do_normalize
       _A        =       image_mean if image_mean is not None else OPENAI_CLIP_MEAN
       _A        =       image_std if image_std is not None else OPENAI_CLIP_STD
       _A        =       do_convert_rgb

 def       lowerCAmelCase_							(			self	:	List[str]   ,							_UpperCAmelCase	:	np.ndarray   ,							_UpperCAmelCase	:	Dict[str, int]   ,							_UpperCAmelCase	:	PILImageResampling = PILImageResampling.BICUBIC   ,							_UpperCAmelCase	:	Optional[Union[str, ChannelDimension]] = None   ,							**_UpperCAmelCase	:	Dict   ,							):
       _A        =       get_size_dict(_UpperCAmelCase   ,							default_to_square=_UpperCAmelCase		)
       if "shortest_edge" not in size:
             raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''		)
       _A        =       get_resize_output_image_size(_UpperCAmelCase   ,							size=size['shortest_edge']   ,							default_to_square=_UpperCAmelCase		)
       return resize(_UpperCAmelCase   ,							size=_UpperCAmelCase   ,							resample=_UpperCAmelCase   ,							data_format=_UpperCAmelCase   ,							**_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	np.ndarray   ,							_UpperCAmelCase	:	Dict[str, int]   ,							_UpperCAmelCase	:	Optional[Union[str, ChannelDimension]] = None   ,							**_UpperCAmelCase	:	Tuple   ,							):
       _A        =       get_size_dict(_UpperCAmelCase		)
       if "height" not in size or "width" not in size:
             raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''		)
       return center_crop(_UpperCAmelCase   ,							size=(size['height'], size['width'])   ,							data_format=_UpperCAmelCase   ,							**_UpperCAmelCase		)

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

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



 def       lowerCAmelCase_							(			self	:	Optional[int]   ,							_UpperCAmelCase	:	ImageInput   ,							_UpperCAmelCase	:	bool = None   ,							_UpperCAmelCase	:	Dict[str, int] = None   ,							_UpperCAmelCase	:	PILImageResampling = None   ,							_UpperCAmelCase	:	bool = None   ,							_UpperCAmelCase	:	int = None   ,							_UpperCAmelCase	:	bool = None   ,							_UpperCAmelCase	:	float = None   ,							_UpperCAmelCase	:	bool = None   ,							_UpperCAmelCase	:	Optional[Union[float, List[float]]] = None   ,							_UpperCAmelCase	:	Optional[Union[float, List[float]]] = None   ,							_UpperCAmelCase	:	bool = None   ,							_UpperCAmelCase	:	Optional[Union[str, TensorType]] = None   ,							_UpperCAmelCase	:	Optional[ChannelDimension] = ChannelDimension.FIRST   ,							**_UpperCAmelCase	:	Optional[int]   ,							):
       _A        =       do_resize if do_resize is not None else self.do_resize
       _A        =       size if size is not None else self.size
       _A        =       get_size_dict(_UpperCAmelCase   ,							param_name='size'   ,							default_to_square=_UpperCAmelCase		)
       _A        =       resample if resample is not None else self.resample
       _A        =       do_center_crop if do_center_crop is not None else self.do_center_crop
       _A        =       crop_size if crop_size is not None else self.crop_size
       _A        =       get_size_dict(_UpperCAmelCase   ,							param_name='crop_size'   ,							default_to_square=_UpperCAmelCase		)
       _A        =       do_rescale if do_rescale is not None else self.do_rescale
       _A        =       rescale_factor if rescale_factor is not None else self.rescale_factor
       _A        =       do_normalize if do_normalize is not None else self.do_normalize
       _A        =       image_mean if image_mean is not None else self.image_mean
       _A        =       image_std if image_std is not None else self.image_std
       _A        =       do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

       _A        =       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:
             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.'		)

       # PIL RGBA images are converted to RGB
       if do_convert_rgb:
             _A        =       [convert_to_rgb(_UpperCAmelCase		) for image in images]

       # All transformations expect numpy arrays.
       _A        =       [to_numpy_array(_UpperCAmelCase		) for image in images]

       if do_resize:
             _A        =       [self.resize(image=_UpperCAmelCase   ,							size=_UpperCAmelCase   ,							resample=_UpperCAmelCase		) for image in images]

       if do_center_crop:
             _A        =       [self.center_crop(image=_UpperCAmelCase   ,							size=_UpperCAmelCase		) for image in images]

       if do_rescale:
             _A        =       [self.rescale(image=_UpperCAmelCase   ,							scale=_UpperCAmelCase		) for image in images]

       if do_normalize:
             _A        =       [self.normalize(image=_UpperCAmelCase   ,							mean=_UpperCAmelCase   ,							std=_UpperCAmelCase		) for image in images]

       _A        =       [to_channel_dimension_format(_UpperCAmelCase   ,							_UpperCAmelCase		) for image in images]

       _A        =       {'pixel_values': images}
       return BatchFeature(data=_UpperCAmelCase   ,							tensor_type=_UpperCAmelCase		)







"""simple docstring"""

from sklearn.metrics import fa_score

import datasets


a         =      '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


a         =      '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    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.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    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\'`.

        - \'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.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'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.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    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.

Examples:

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

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> 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])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


a         =      '''
@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     lowercase_	(					datasets.Metric							):



 '''simple docstring'''

 def       lowerCAmelCase_							(			self	:	Any		):
       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	:	int   ,							_UpperCAmelCase	:	Any   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	List[str]=None   ,							_UpperCAmelCase	:	Dict=1   ,							_UpperCAmelCase	:	Union[str, Any]="binary"   ,							_UpperCAmelCase	:	List[str]=None		):
       _A        =       fa_score(
           _UpperCAmelCase   ,							_UpperCAmelCase   ,							labels=_UpperCAmelCase   ,							pos_label=_UpperCAmelCase   ,							average=_UpperCAmelCase   ,							sample_weight=_UpperCAmelCase		)
       return {"f1": float(_UpperCAmelCase		) if score.size == 1 else score}

