





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

A   : Optional[int]             =			logging.get_logger(__name__)







@add_end_docstrings(__UpperCAmelCase  )
class 			lowerCamelCase					(						__UpperCAmelCase  ):


					def __init__(					self	:  Optional[Any]       ,     *__snake_case	:  Optional[int]       ,     **__snake_case	:  Any       ):





											'''simple docstring'''





											super().__init__(*__snake_case       ,     **__snake_case       )
											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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  Optional[int]=None       ,     __snake_case	:  Optional[int]=None       ,     __snake_case	:  Any=None       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		{}
											_snake_case:   Optional[int]  					=		{}

											if prompt is not None:
																	_snake_case:   Any  					=		prompt

											if generate_kwargs is not None:
																	_snake_case:   Optional[int]  					=		generate_kwargs
											if max_new_tokens is not None:
																	if "generate_kwargs" not in forward_kwargs:
																							_snake_case:   str  					=		{}
																	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'       )
																	_snake_case:   List[Any]  					=		max_new_tokens
											return preprocess_params, forward_kwargs, {}


					def __call__(					self	:  List[str]       ,     __snake_case	:  Union[str, List[str], "Image.Image", List["Image.Image"]]       ,     **__snake_case	:  Tuple       ):





											'''simple docstring'''





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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Any=None       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		load_image(__snake_case       )

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

																	_snake_case:   List[Any]  					=		self.model.config.model_type

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

																	elif model_type == "pix2struct":
																							_snake_case:   Dict  					=		self.image_processor(images=__snake_case       ,     header_text=__snake_case       ,     return_tensors=self.framework       )

																	elif model_type != "vision-encoder-decoder":
																							# vision-encoder-decoder does not support conditional generation
																							_snake_case:   List[str]  					=		self.image_processor(images=__snake_case       ,     return_tensors=self.framework       )
																							_snake_case:   List[Any]  					=		self.tokenizer(__snake_case       ,     return_tensors=self.framework       )
																							model_inputs.update(__snake_case       )

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

											else:
																	_snake_case:   Optional[int]  					=		self.image_processor(images=__snake_case       ,     return_tensors=self.framework       )

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

											return model_inputs


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Any=None       ):





											'''simple docstring'''





											if (
											    "input_ids" in model_inputs
											    and isinstance(model_inputs['input_ids']       ,     __snake_case       )
											    and all(x is None for x in model_inputs['input_ids']       )
											):
																	_snake_case:   Union[str, Any]  					=		None

											if generate_kwargs is None:
																	_snake_case:   Optional[int]  					=		{}
											# 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.
											_snake_case:   List[Any]  					=		model_inputs.pop(self.model.main_input_name       )
											_snake_case:   Optional[Any]  					=		self.model.generate(__snake_case       ,     **__snake_case       ,     **__snake_case       )
											return model_outputs




					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		[]
											for output_ids in model_outputs:
																	_snake_case:   List[str]  					=		{
																	    'generated_text': self.tokenizer.decode(
																	        __snake_case       ,     skip_special_tokens=__snake_case       ,     )
																	}
																	records.append(__snake_case       )
											return records












'''simple docstring'''






from sklearn.metrics import matthews_corrcoef

import datasets


A   : Dict             =			'\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n'

A   : int             =			'\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric("matthews_correlation")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results[\'matthews_correlation\'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric("matthews_correlation")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results[\'matthews_correlation\'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric("matthews_correlation")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results[\'matthews_correlation\'], 2))\n        -0.25\n'

A   : Dict             =			'\\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 			lowerCamelCase					(						datasets.Metric  ):


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  int       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Union[str, Any]=None       ):





											'''simple docstring'''





											return {
											    "matthews_correlation": float(matthews_corrcoef(__snake_case       ,     __snake_case       ,     sample_weight=__snake_case       )       ),
											}





