





'''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


__UpperCamelCase					    =	logging.get_logger(__name__)


if is_vision_available():
	import PIL




class  _A (					__lowercase		):
		lowercase__:   str				     =   ['''pixel_values''']

		def __init__(   self					:   Union[str, Any]  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   PILImageResampling = PILImageResampling.BICUBIC  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Union[int, float] = 1 / 2_55  ,      __magic_name__					:   bool = True  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   bool = True  ,      **__magic_name__					:   Optional[Any]  ,      )					->    None:


					"""simple docstring"""

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

					__snake_case					:      Any							      =     do_resize
					__snake_case					:      Optional[Any]							      =     size
					__snake_case					:      List[str]							      =     resample
					__snake_case					:      Optional[int]							      =     do_center_crop
					__snake_case					:      List[str]							      =     crop_size
					__snake_case					:      Dict							      =     do_rescale
					__snake_case					:      List[Any]							      =     rescale_factor
					__snake_case					:      Tuple							      =     do_normalize
					__snake_case					:      Tuple							      =     image_mean if image_mean is not None else OPENAI_CLIP_MEAN
					__snake_case					:      Dict							      =     image_std if image_std is not None else OPENAI_CLIP_STD
					__snake_case					:      Tuple							      =     do_convert_rgb

		def 	lowercase__     (   self					:   int  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Dict[str, int]  ,      __magic_name__					:   PILImageResampling = PILImageResampling.BICUBIC  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   Tuple  ,      )					->    np.ndarray:


					"""simple docstring"""

					__snake_case					:      Optional[int]							      =     get_size_dict(__magic_name__  ,      default_to_square=__magic_name__			)
					if "shortest_edge" not in size:
								raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''			)
					__snake_case					:      Tuple							      =     get_resize_output_image_size(__magic_name__  ,      size=size["""shortest_edge"""]  ,      default_to_square=__magic_name__			)
					return resize(__magic_name__  ,      size=__magic_name__  ,      resample=__magic_name__  ,      data_format=__magic_name__  ,      **__magic_name__			)

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


					"""simple docstring"""

					__snake_case					:      str							      =     get_size_dict(__magic_name__			)
					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(__magic_name__  ,      size=(size["""height"""], size["""width"""])  ,      data_format=__magic_name__  ,      **__magic_name__			)

		def 	lowercase__     (   self					:   List[Any]  ,      __magic_name__					:   np.ndarray  ,      __magic_name__					:   Union[int, float]  ,      __magic_name__					:   Optional[Union[str, ChannelDimension]] = None  ,      **__magic_name__					:   Optional[int]  ,      )					->    Tuple:


					"""simple docstring"""

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

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


					"""simple docstring"""

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

		def 	lowercase__     (   self					:   Dict  ,      __magic_name__					:   ImageInput  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Dict[str, int] = None  ,      __magic_name__					:   PILImageResampling = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   int = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   float = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   Optional[Union[float, List[float]]] = None  ,      __magic_name__					:   bool = None  ,      __magic_name__					:   Optional[Union[str, TensorType]] = None  ,      __magic_name__					:   Optional[ChannelDimension] = ChannelDimension.FIRST  ,      **__magic_name__					:   Tuple  ,      )					->    PIL.Image.Image:


					"""simple docstring"""

					__snake_case					:      List[str]							      =     do_resize if do_resize is not None else self.do_resize
					__snake_case					:      Any							      =     size if size is not None else self.size
					__snake_case					:      List[str]							      =     get_size_dict(__magic_name__  ,      param_name="""size"""  ,      default_to_square=__magic_name__			)
					__snake_case					:      Dict							      =     resample if resample is not None else self.resample
					__snake_case					:      Union[str, Any]							      =     do_center_crop if do_center_crop is not None else self.do_center_crop
					__snake_case					:      Union[str, Any]							      =     crop_size if crop_size is not None else self.crop_size
					__snake_case					:      str							      =     get_size_dict(__magic_name__  ,      param_name="""crop_size"""  ,      default_to_square=__magic_name__			)
					__snake_case					:      str							      =     do_rescale if do_rescale is not None else self.do_rescale
					__snake_case					:      Dict							      =     rescale_factor if rescale_factor is not None else self.rescale_factor
					__snake_case					:      int							      =     do_normalize if do_normalize is not None else self.do_normalize
					__snake_case					:      Tuple							      =     image_mean if image_mean is not None else self.image_mean
					__snake_case					:      List[Any]							      =     image_std if image_std is not None else self.image_std
					__snake_case					:      Union[str, Any]							      =     do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

					__snake_case					:      Optional[int]							      =     make_list_of_images(__magic_name__			)

					if not valid_images(__magic_name__			):
								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:
								__snake_case					:      List[str]							      =     [convert_to_rgb(__magic_name__			) for image in images]

					# All transformations expect numpy arrays.
					__snake_case					:      str							      =     [to_numpy_array(__magic_name__			) for image in images]

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

					if do_center_crop:
								__snake_case					:      Any							      =     [self.center_crop(image=__magic_name__  ,      size=__magic_name__			) for image in images]

					if do_rescale:
								__snake_case					:      Optional[Any]							      =     [self.rescale(image=__magic_name__  ,      scale=__magic_name__			) for image in images]

					if do_normalize:
								__snake_case					:      int							      =     [self.normalize(image=__magic_name__  ,      mean=__magic_name__  ,      std=__magic_name__			) for image in images]

					__snake_case					:      Union[str, Any]							      =     [to_channel_dimension_format(__magic_name__  ,      __magic_name__			) for image in images]

					__snake_case					:      List[Any]							      =     {"""pixel_values""": images}
					return BatchFeature(data=__magic_name__  ,      tensor_type=__magic_name__			)









'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__UpperCamelCase					    =	"\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


__UpperCamelCase					    =	"\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while 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 y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions 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. Note that it 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- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


__UpperCamelCase					    =	"\n@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}\n"




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

		def 	lowercase__     (   self					:   Optional[int]			)					->    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.recall_score.html"""]  ,      )

		def 	lowercase__     (   self					:   Tuple  ,      __magic_name__					:   int  ,      __magic_name__					:   Union[str, Any]  ,      __magic_name__					:   Any=None  ,      __magic_name__					:   Optional[Any]=1  ,      __magic_name__					:   List[str]="binary"  ,      __magic_name__					:   Tuple=None  ,      __magic_name__					:   Dict="warn"  ,      )					->    Any:


					"""simple docstring"""

					__snake_case					:      Tuple							      =     recall_score(
					    __magic_name__  ,      __magic_name__  ,      labels=__magic_name__  ,      pos_label=__magic_name__  ,      average=__magic_name__  ,      sample_weight=__magic_name__  ,      zero_division=__magic_name__  ,      )
					return {"recall": float(__magic_name__			) if score.size == 1 else score}


