

'''simple docstring'''
import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class        a__  (							lowerCamelCase_  ):
   _SCREAMING_SNAKE_CASE   :					List[Any]     	=							['image_processor', 'tokenizer']
   _SCREAMING_SNAKE_CASE   :					str     	=							'OwlViTImageProcessor'
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							('CLIPTokenizer', 'CLIPTokenizerFast')


   def __init__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    **_UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       None
      if "feature_extractor" in kwargs:
         warnings.warn(
             "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
             " instead."      ,    _UpperCamelCase      ,    )
         _lowercase      :				Optional[int]      					=       kwargs.pop("feature_extractor"  )

      _lowercase      :				str      					=       image_processor if image_processor is not None else feature_extractor
      if image_processor is None:
         raise ValueError("You need to specify an `image_processor`."  )
      if tokenizer is None:
         raise ValueError("You need to specify a `tokenizer`."  )

      super().__init__(_UpperCamelCase      ,    _UpperCamelCase  )


   def __call__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase="max_length"      ,    _UpperCamelCase="np"      ,    **_UpperCamelCase  ):





      """simple docstring"""





      if text is None and query_images is None and images is None:
         raise ValueError(
             "You have to specify at least one text or query image or image. All three cannot be none."  )

      if text is not None:
         if isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) or (isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and not isinstance(text[0]      ,    _UpperCamelCase  )):
            _lowercase      :				int      					=       [self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )]

         elif isinstance(_UpperCamelCase      ,    _UpperCamelCase  ) and isinstance(text[0]      ,    _UpperCamelCase  ):
            _lowercase      :				str      					=       []

            # Maximum number of queries across batch
            _lowercase      :				str      					=       max([len(_UpperCamelCase  ) for t in text]  )

            # Pad all batch samples to max number of text queries
            for t in text:
               if len(_UpperCamelCase  ) != max_num_queries:
                  _lowercase      :				List[Any]      					=       t + [" "] * (max_num_queries - len(_UpperCamelCase  ))

               _lowercase      :				Tuple      					=       self.tokenizer(_UpperCamelCase      ,    padding=_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )
               encodings.append(_UpperCamelCase  )
         else:
            raise TypeError("Input text should be a string, a list of strings or a nested list of strings"  )

         if return_tensors == "np":
            _lowercase      :				List[Any]      					=       np.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				Optional[Any]      					=       np.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         elif return_tensors == "jax" and is_flax_available():
            import jax.numpy as jnp

            _lowercase      :				Union[str, Any]      					=       jnp.concatenate([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				int      					=       jnp.concatenate([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         elif return_tensors == "pt" and is_torch_available():
            import torch

            _lowercase      :				int      					=       torch.cat([encoding["input_ids"] for encoding in encodings]      ,    dim=0  )
            _lowercase      :				Dict      					=       torch.cat([encoding["attention_mask"] for encoding in encodings]      ,    dim=0  )

         elif return_tensors == "tf" and is_tf_available():
            import tensorflow as tf

            _lowercase      :				Optional[int]      					=       tf.stack([encoding["input_ids"] for encoding in encodings]      ,    axis=0  )
            _lowercase      :				List[str]      					=       tf.stack([encoding["attention_mask"] for encoding in encodings]      ,    axis=0  )

         else:
            raise ValueError("Target return tensor type could not be returned"  )

         _lowercase      :				Optional[int]      					=       BatchEncoding()
         _lowercase      :				List[Any]      					=       input_ids
         _lowercase      :				Dict      					=       attention_mask

      if query_images is not None:
         _lowercase      :				int      					=       BatchEncoding()
         _lowercase      :				Any      					=       self.image_processor(
             _UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  ).pixel_values
         _lowercase      :				Any      					=       query_pixel_values

      if images is not None:
         _lowercase      :				str      					=       self.image_processor(_UpperCamelCase      ,    return_tensors=_UpperCamelCase      ,    **_UpperCamelCase  )

      if text is not None and images is not None:
         _lowercase      :				List[Any]      					=       image_features.pixel_values
         return encoding
      elif query_images is not None and images is not None:
         _lowercase      :				Optional[Any]      					=       image_features.pixel_values
         return encoding
      elif text is not None or query_images is not None:
         return encoding
      else:
         return BatchEncoding(data=dict(**_UpperCamelCase  )      ,    tensor_type=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process_object_detection(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.image_processor.post_process_image_guided_detection(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.tokenizer.batch_decode(*_UpperCamelCase      ,    **_UpperCamelCase  )


   def 						_lowerCamelCase       (			self      ,    *_UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      return self.tokenizer.decode(*_UpperCamelCase      ,    **_UpperCamelCase  )


   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      warnings.warn(
          "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."      ,    _UpperCamelCase      ,    )
      return self.image_processor_class






   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      warnings.warn(
          "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,    _UpperCamelCase      ,    )
      return self.image_processor









'''simple docstring'''
from sklearn.metrics import mean_squared_error

import datasets


_snake_case         =  '\\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'

_snake_case         =  '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n'


_snake_case         =  '\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        "raw_values" : Returns a full set of errors in case of multioutput input.\n\n        "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric("mse")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {\'mse\': 0.6123724356957945}\n\n    If you\'re using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric("mse", "multilist")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'mse\': array([0.41666667, 1. ])}\n'


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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      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 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      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 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase=None      ,    _UpperCamelCase="uniform_average"      ,    _UpperCamelCase=True  ):





      """simple docstring"""





      _lowercase      :				str      					=       mean_squared_error(
          _UpperCamelCase      ,    _UpperCamelCase      ,    sample_weight=_UpperCamelCase      ,    multioutput=_UpperCamelCase      ,    squared=_UpperCamelCase  )

      return {"mse": mse}






