






'''simple docstring'''



from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
      from PIL import Image

      from ..image_utils import load_image

if is_tf_available():
      import tensorflow as tf

      from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
      from ..tf_utils import stable_softmax

if is_torch_available():
      from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)
@add_end_docstrings(__A					)
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      def __init__(			self      :		Tuple  ,   *UpperCAmelCase      :		int  ,   **UpperCAmelCase      :		Optional[Any]		)	->	Dict:


       '''simple docstring'''

       super().__init__(*UpperCAmelCase  ,   **UpperCAmelCase		)
       requires_backends(self  ,   '''vision'''		)
       self.check_model_type(
           TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
           if self.framework == '''tf'''
           else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		str=None		)	->	Union[str, Any]:


       '''simple docstring'''

       lowercase       : Dict						={}
       if top_k is not None:
        lowercase       : Union[str, Any]						=top_k
       return {}, {}, postprocess_params






      def __call__(			self      :		str  ,   UpperCAmelCase      :		Union[str, List[str], "Image.Image", List["Image.Image"]]  ,   **UpperCAmelCase      :		str		)	->	Optional[Any]:


       '''simple docstring'''

       return super().__call__(UpperCAmelCase  ,   **UpperCAmelCase		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		Optional[int]		)	->	int:


       '''simple docstring'''

       lowercase       : List[Any]						=load_image(UpperCAmelCase		)
       lowercase       : Optional[Any]						=self.image_processor(images=UpperCAmelCase  ,   return_tensors=self.framework		)
       return model_inputs






      def 					A__   (			self      :		Union[str, Any]  ,   UpperCAmelCase      :		Optional[Any]		)	->	Any:


       '''simple docstring'''

       lowercase       : str						=self.model(**UpperCAmelCase		)
       return model_outputs






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Any=5		)	->	str:


       '''simple docstring'''

       if top_k > self.model.config.num_labels:
        lowercase       : Any						=self.model.config.num_labels

       if self.framework == "pt":
        lowercase       : Dict						=model_outputs.logits.softmax(-1		)[0]
        lowercase	,		lowercase       : Dict						=probs.topk(UpperCAmelCase		)
       elif self.framework == "tf":
        lowercase       : Tuple						=stable_softmax(model_outputs.logits  ,   axis=-1		)[0]
        lowercase       : Dict						=tf.math.top_k(UpperCAmelCase  ,   k=UpperCAmelCase		)
        lowercase	,		lowercase       : Any						=topk.values.numpy(), topk.indices.numpy()
       else:
        raise ValueError(f'Unsupported framework: {self.framework}'		)

       lowercase       : str						=scores.tolist()
       lowercase       : Dict						=ids.tolist()
       return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCAmelCase  ,   UpperCAmelCase		)]











from sklearn.metrics import matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		"""
Compute the Matthews correlation coefficient (MCC)

The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary and multiclass classifications. It takes
into account true and false positives and negatives and is generally
regarded as a balanced measure which can be used even if the classes are of
very different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction.  The statistic
is also known as the phi coefficient. [source: Wikipedia]
"""

SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		"""
Args:
    predictions (list of int): Predicted labels, as returned by a model.
    references (list of int): Ground truth labels.
    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.
Returns:
    matthews_correlation (dict containing float): Matthews correlation.
Examples:
    Example 1, a basic example with only predictions and references as inputs:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3])
        >>> print(round(results['matthews_correlation'], 2))
        0.54

    Example 2, the same example as above, but also including sample weights:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])
        >>> print(round(results['matthews_correlation'], 2))
        0.1

    Example 3, the same example as above, but with sample weights that cause a negative correlation:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])
        >>> print(round(results['matthews_correlation'], 2))
        -0.25
"""

SCREAMING_SNAKE_CASE__   :      int				=		"""\
@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     lowerCamelCase_					(   datasets.Metric			):







				def       A						(    self  ):
								"""simple docstring"""
								return datasets.MetricInfo(
								    description=_DESCRIPTION							,       citation=_CITATION							,       inputs_description=_KWARGS_DESCRIPTION							,       features=datasets.Features(
								        {
								            '''predictions''': datasets.Value('''int32'''  ),
								            '''references''': datasets.Value('''int32'''  ),
								        }  )							,       reference_urls=[
								        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'''
								    ]							,       )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								return {
								    "matthews_correlation": float(matthews_corrcoef(__lowerCAmelCase							,       __lowerCAmelCase							,       sample_weight=__lowerCAmelCase  )  ),
								}






