
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[Any]								=     logging.get_logger(__name__)



@add_end_docstrings(_a    )
class    a_ (			_a    ):






			def __init__(      self				,			*__UpperCamelCase				,			**__UpperCamelCase  ):
									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				,			__UpperCamelCase=None				,			__UpperCamelCase=None				,			__UpperCamelCase=None  ):
									_lowercase					       =					{}
									_lowercase					       =					{}

									if prompt is not None:
															_lowercase					       =					prompt

									if generate_kwargs is not None:
															_lowercase					       =					generate_kwargs
									if max_new_tokens is not None:
															if "generate_kwargs" not in forward_kwargs:
																					_lowercase					       =					{}
															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"""  )
															_lowercase					       =					max_new_tokens
									return preprocess_params, forward_kwargs, {}






			def __call__(      self				,			__UpperCamelCase				,			**__UpperCamelCase  ):
									return super().__call__(__UpperCamelCase				,			**__UpperCamelCase  )






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase=None  ):
									_lowercase					       =					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."""  )

															_lowercase					       =					self.model.config.model_type

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

															elif model_type == "pix2struct":
																					_lowercase					       =					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
																					_lowercase					       =					self.image_processor(images=__UpperCamelCase				,			return_tensors=self.framework  )
																					_lowercase					       =					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:
															_lowercase					       =					self.image_processor(images=__UpperCamelCase				,			return_tensors=self.framework  )

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

									return model_inputs






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase=None  ):
									# 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"""]  )
									):
															_lowercase					       =					None

									if generate_kwargs is None:
															_lowercase					       =					{}
									# 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.
									_lowercase					       =					model_inputs.pop(self.model.main_input_name  )
									_lowercase					       =					self.model.generate(__UpperCamelCase				,			**__UpperCamelCase				,			**__UpperCamelCase  )
									return model_outputs






			def    UpperCamelCase_				(      self				,			__UpperCamelCase  ):
									_lowercase					       =					[]
									for output_ids in model_outputs:
															_lowercase					       =					{
															    """generated_text""": self.tokenizer.decode(
															        __UpperCamelCase				,			skip_special_tokens=__UpperCamelCase				,			)
															}
															records.append(__UpperCamelCase  )
									return records

from sklearn.metrics import mean_squared_error

import datasets


A		: List[Any]								=     '''\
@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}
}
'''

A		: str								=     '''\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
'''


A		: Any								=     '''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        "raw_values" : Returns a full set of errors in case of multioutput input.

        "uniform_average" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric("mse")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {\'mse\': 0.6123724356957945}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric("mse", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {\'mse\': array([0.41666667, 1. ])}
'''



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






			def    UpperCamelCase_				(      self  ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION				,			citation=_CITATION				,			inputs_description=_KWARGS_DESCRIPTION				,			features=datasets.Features(self._get_feature_types()  )				,			reference_urls=[
									        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"""
									    ]				,			)






			def    UpperCamelCase_				(      self  ):
									if self.config_name == "multilist":
															return {
															    "predictions": datasets.Sequence(datasets.Value("""float"""  )  ),
															    "references": datasets.Sequence(datasets.Value("""float"""  )  ),
															}
									else:
															return {
															    "predictions": datasets.Value("""float"""  ),
															    "references": datasets.Value("""float"""  ),
															}






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase=None				,			__UpperCamelCase="uniform_average"				,			__UpperCamelCase=True  ):
									_lowercase					       =					mean_squared_error(
									    __UpperCamelCase				,			__UpperCamelCase				,			sample_weight=__UpperCamelCase				,			multioutput=__UpperCamelCase				,			squared=__UpperCamelCase  )

									return {"mse": mse}