


'''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():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
       import torch

       from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

__snake_case    						=logging.get_logger(__name__)

@add_end_docstrings(__lowercase		)
class 		UpperCAmelCase_      (  __lowercase		):





     def __init__( self       :      Tuple    ,      *UpperCAmelCase__       :      int    ,      **UpperCAmelCase__       :      Optional[int]    )				->  int:
        super().__init__(*UpperCAmelCase__    ,      **UpperCAmelCase__    )
        requires_backends(self    ,      'vision'    )
        self.check_model_type(
            TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING    )





     def 							__UpperCAmelCase      ( self       :      Dict    ,      UpperCAmelCase__       :      List[str]=None    ,      UpperCAmelCase__       :      Tuple=None    ,      UpperCAmelCase__       :      Dict=None    )				->  Tuple:
        lowerCAmelCase     =			{}
        lowerCAmelCase     =			{}

        if prompt is not None:
           lowerCAmelCase     =			prompt

        if generate_kwargs is not None:
           lowerCAmelCase     =			generate_kwargs
        if max_new_tokens is not None:
           if "generate_kwargs" not in forward_kwargs:
              lowerCAmelCase     =			{}
           if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
              raise ValueError(
                  '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'
                  ' please use only one'    )
           lowerCAmelCase     =			max_new_tokens
        return preprocess_params, forward_kwargs, {}





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





     def 							__UpperCAmelCase      ( self       :      int    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Optional[Any]=None    )				->  Dict:
        lowerCAmelCase     =			load_image(UpperCAmelCase__    )

        if prompt is not None:
           if not isinstance(UpperCAmelCase__    ,      UpperCAmelCase__    ):
              raise ValueError(
                  F'''Received an invalid text input, got - {type(UpperCAmelCase__    )} - but expected a single string. '''
                  'Note also that one single text can be provided for conditional image to text generation.'    )

           lowerCAmelCase     =			self.model.config.model_type

           if model_type == "git":
              lowerCAmelCase     =			self.image_processor(images=UpperCAmelCase__    ,      return_tensors=self.framework    )
              lowerCAmelCase     =			self.tokenizer(text=UpperCAmelCase__    ,      add_special_tokens=UpperCAmelCase__    ).input_ids
              lowerCAmelCase     =			[self.tokenizer.cls_token_id] + input_ids
              lowerCAmelCase     =			torch.tensor(UpperCAmelCase__    ).unsqueeze(0    )
              model_inputs.update({'input_ids': input_ids}    )

           elif model_type == "pix2struct":
              lowerCAmelCase     =			self.image_processor(images=UpperCAmelCase__    ,      header_text=UpperCAmelCase__    ,      return_tensors=self.framework    )

           elif model_type != "vision-encoder-decoder":
              # vision-encoder-decoder does not support conditional generation
              lowerCAmelCase     =			self.image_processor(images=UpperCAmelCase__    ,      return_tensors=self.framework    )
              lowerCAmelCase     =			self.tokenizer(UpperCAmelCase__    ,      return_tensors=self.framework    )
              model_inputs.update(UpperCAmelCase__    )

           else:
              raise ValueError(F'''Model type {model_type} does not support conditional text generation'''    )

        else:
           lowerCAmelCase     =			self.image_processor(images=UpperCAmelCase__    ,      return_tensors=self.framework    )

        if self.model.config.model_type == "git" and prompt is None:
           lowerCAmelCase     =			None

        return model_inputs





     def 							__UpperCAmelCase      ( self       :      Optional[int]    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      List[Any]=None    )				->  str:
        # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
        # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
        if (
            "input_ids" in model_inputs
            and isinstance(model_inputs['input_ids']    ,      UpperCAmelCase__    )
            and all(x is None for x in model_inputs['input_ids']    )
        ):
           lowerCAmelCase     =			None

        if generate_kwargs is None:
           lowerCAmelCase     =			{}
        # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
        #  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
        #  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
        #  in the `_prepare_model_inputs` method.
        lowerCAmelCase     =			model_inputs.pop(self.model.main_input_name    )
        lowerCAmelCase     =			self.model.generate(UpperCAmelCase__    ,      **UpperCAmelCase__    ,      **UpperCAmelCase__    )
        return model_outputs





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    ,      UpperCAmelCase__       :      Tuple    )				->  Optional[int]:
        lowerCAmelCase     =			[]
        for output_ids in model_outputs:
           lowerCAmelCase     =			{
               'generated_text': self.tokenizer.decode(
                   UpperCAmelCase__    ,      skip_special_tokens=UpperCAmelCase__    ,      )
           }
           records.append(UpperCAmelCase__    )
        return records












"""simple docstring"""





from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__					=   "\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n"

SCREAMING_SNAKE_CASE__					=   "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n"

SCREAMING_SNAKE_CASE__					=   "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"pearson\": Pearson Correlation\n    \"spearmanr\": Spearman Correlation\n    \"matthews_correlation\": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'stsb')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n    {'pearson': 1.0, 'spearmanr': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'cola')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Tuple							,						SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      return float((preds == labels).mean()			)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Optional[Any]							,						SCREAMING_SNAKE_CASE     :						Any			):







      '''simple docstring'''




      lowerCAmelCase  						=       simple_accuracy(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       float(fa_score(y_true=SCREAMING_SNAKE_CASE							,						y_pred=SCREAMING_SNAKE_CASE			)			)
      return {
          "accuracy": acc,
          "f1": fa,
      }


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						List[str]							,						SCREAMING_SNAKE_CASE     :						Tuple			):







      '''simple docstring'''




      lowerCAmelCase  						=       float(pearsonr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      lowerCAmelCase  						=       float(spearmanr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      return {
          "pearson": pearson_corr,
          "spearmanr": spearman_corr,
      }






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





      def     _snake_case			(       self )		->     List[str]:
            if self.config_name not in [
                "sst2",
                "mnli",
                "mnli_mismatched",
                "mnli_matched",
                "cola",
                "stsb",
                "mrpc",
                "qqp",
                "qnli",
                "rte",
                "wnli",
                "hans",
            ]:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                        """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                    } )      ,						codebase_urls=[]      ,						reference_urls=[]      ,						format="""numpy"""      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Any:
            if self.config_name == "cola":
                  return {"matthews_correlation": matthews_corrcoef(lowercase      ,						lowercase )}
            elif self.config_name == "stsb":
                  return pearson_and_spearman(lowercase      ,						lowercase )
            elif self.config_name in ["mrpc", "qqp"]:
                  return acc_and_fa(lowercase      ,						lowercase )
            elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
                  return {"accuracy": simple_accuracy(lowercase      ,						lowercase )}
            else:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )






