

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

import datasets


lowerCamelCase :      int					 =     "\\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"

lowerCamelCase :      List[str]					 =     "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n"


lowerCamelCase :      Optional[Any]					 =     "\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 						A  (		self      :	Any )	->    List[str]:





       '''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 						A  (		self      :	List[str] )	->    List[str]:





       '''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 						A  (		self      :	Tuple							,					_a      :	Optional[Any]							,					_a      :	str							,					_a      :	str=None							,					_a      :	Optional[int]="uniform_average"							,					_a      :	Optional[Any]=True )	->    int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =mean_squared_error(
           _a							,					_a							,					sample_weight=_a							,					multioutput=_a							,					squared=_a )

       return {"mse": mse}



'''simple docstring'''
import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

     from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
     lowerCamelCase :      int					 =     False

if is_vision_available():
     from PIL import Image

     from transformers import PixaStructImageProcessor







class 							A__    (       unittest.TestCase  ):





  def __init__(		self      :	List[str]							,					_a      :	List[Any]							,					_a      :	List[str]=7							,					_a      :	List[str]=3							,					_a      :	Tuple=18							,					_a      :	Tuple=30							,					_a      :	str=400							,					_a      :	Tuple=None							,					_a      :	Union[str, Any]=True							,					_a      :	List[str]=True							,					_a      :	Optional[int]=None							,					)	->    List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =size if size is not None else {'height': 20, 'width': 20}
       _SCREAMING_SNAKE_CASE							    =parent
       _SCREAMING_SNAKE_CASE							    =batch_size
       _SCREAMING_SNAKE_CASE							    =num_channels
       _SCREAMING_SNAKE_CASE							    =image_size
       _SCREAMING_SNAKE_CASE							    =min_resolution
       _SCREAMING_SNAKE_CASE							    =max_resolution
       _SCREAMING_SNAKE_CASE							    =size
       _SCREAMING_SNAKE_CASE							    =do_normalize
       _SCREAMING_SNAKE_CASE							    =do_convert_rgb
       _SCREAMING_SNAKE_CASE							    =[512, 1024, 2048, 4096]
       _SCREAMING_SNAKE_CASE							    =patch_size if patch_size is not None else {'height': 16, 'width': 16}





  def 						A  (		self      :	Any )	->    List[str]:





       '''simple docstring'''






       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}





  def 						A  (		self      :	int )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       _SCREAMING_SNAKE_CASE							    =Image.open(requests.get(_a							,					stream=_a ).raw ).convert('RGB' )
       return raw_image







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11     ,   reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'     ,   )
@require_torch
@require_vision
class 							A__    (       A__     ,   unittest.TestCase  ):
  A__		 =				PixaStructImageProcessor if is_vision_available() else None





  def 						A  (		self      :	Dict )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =PixaStructImageProcessingTester(self )





  @property
  def 						A  (		self      :	Optional[Any] )	->    int:





       '''simple docstring'''






       return self.image_processor_tester.prepare_image_processor_dict()





  def 						A  (		self      :	Any )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(_a							,					'do_normalize' ) )
       self.assertTrue(hasattr(_a							,					'do_convert_rgb' ) )





  def 						A  (		self      :	Any )	->    List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processor_tester.prepare_dummy_image()

       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       _SCREAMING_SNAKE_CASE							    =2048

       _SCREAMING_SNAKE_CASE							    =image_processor(_a							,					return_tensors='pt'							,					max_patches=_a )
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean()							,					torch.tensor(0.06_06 )							,					atol=1e-3							,					rtol=1e-3 ) )





  def 						A  (		self      :	Any )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





  def 						A  (		self      :	List[str] )	->    Optional[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       _SCREAMING_SNAKE_CASE							    =True

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            with self.assertRaises(_a ):
                 _SCREAMING_SNAKE_CASE							    =image_processor(
                     image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches

            _SCREAMING_SNAKE_CASE							    ='Hello'

            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a							,					header_text=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a							,					header_text=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





  def 						A  (		self      :	List[Any] )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random numpy tensors
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a							,					numpify=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					np.ndarray )

       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)





  def 						A  (		self      :	Union[str, Any] )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PyTorch tensors
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a							,					torchify=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					torch.Tensor )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11     ,   reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'     ,   )
@require_torch
@require_vision
class 							A__    (       A__     ,   unittest.TestCase  ):
  A__		 =				PixaStructImageProcessor if is_vision_available() else None





  def 						A  (		self      :	str )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =PixaStructImageProcessingTester(self							,					num_channels=4 )
       _SCREAMING_SNAKE_CASE							    =3





  @property
  def 						A  (		self      :	List[str] )	->    Optional[Any]:





       '''simple docstring'''






       return self.image_processor_tester.prepare_image_processor_dict()





  def 						A  (		self      :	List[str] )	->    Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       self.assertTrue(hasattr(_a							,					'do_normalize' ) )
       self.assertTrue(hasattr(_a							,					'do_convert_rgb' ) )





  def 						A  (		self      :	Dict )	->    int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =self.image_processing_class(**self.image_processor_dict )
       # create random PIL images
       _SCREAMING_SNAKE_CASE							    =prepare_image_inputs(self.image_processor_tester							,					equal_resolution=_a )
       for image in image_inputs:
            self.assertIsInstance(_a							,					Image.Image )

       # Test not batched input
       _SCREAMING_SNAKE_CASE							    =(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * (self.image_processor_tester.num_channels - 1)
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            _SCREAMING_SNAKE_CASE							    =image_processor(
                image_inputs[0]							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(1, max_patch, expected_hidden_dim)							,					)

            # Test batched
            _SCREAMING_SNAKE_CASE							    =image_processor(
                _a							,					return_tensors='pt'							,					max_patches=_a ).flattened_patches
            self.assertEqual(
                encoded_images.shape							,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,					)
